get Current Location from LocationManager - Android Hardware

Android examples for Hardware:Gps

Description

get Current Location from LocationManager

Demo Code


//package com.java2s;

import android.content.Context;

import android.content.pm.PackageManager;

import android.location.Location;
import android.location.LocationManager;

public class Main {

    public static final Location getCurrentLocation(Context context) {
        try {//  ww  w  .  j  a v a2  s .c  o m
            LocationManager cLocationManager = (LocationManager) context
                    .getSystemService(Context.LOCATION_SERVICE);
            Location cLocation;
            if (checkPermission(context,
                    "android.permission.ACCESS_FINE_LOCATION")) {
                cLocation = cLocationManager.getLastKnownLocation("gps");
                if (cLocation != null) {
                    return cLocation;
                }
            }
            if (checkPermission(context,
                    "android.permission.ACCESS_COARSE_LOCATION")) {
                cLocation = cLocationManager
                        .getLastKnownLocation("network");
                if (cLocation != null) {
                    return cLocation;
                }
            }
            return null;
        } catch (Exception localException) {
        }
        return null;
    }

    public static final boolean checkPermission(Context context,
            String premission) {
        PackageManager localPackageManager = context.getPackageManager();
        if (localPackageManager.checkPermission(premission,
                context.getPackageName()) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return true;
    }
}

Related Tutorials