如何从Android中的LocationManager获取位置

时间:2014-08-08 07:35:12

标签: android location locationmanager

当SIM卡无法使用时,我正在进行从位置管理器获取位置的小型演示。即使位置服务启用,我的位置也为null。我正在使用以下代码

public class LocationTracker extends Service implements LocationListener {

    private final Context mContext;


    boolean isGPSEnabled = false;


    boolean isNetworkEnabled = false;


    boolean canGetLocation = false;

    Location location; 
    double latitude; 
    double longitude; 


    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; 

    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; 


    protected LocationManager locationManager;

    public LocationTracker(Context context){
        this.mContext = context;
        getLocation();
    }

    public Location getLocation(){

        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);


            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);


            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;

    }

    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(LocationTracker.this);
        }       
    }



    public boolean canGetLocation() {
        return this.canGetLocation;
    }


    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }


}`

2 个答案:

答案 0 :(得分:0)

查看博客" Android:基于位置的服务"在http://jcraane.blogspot.fr/2014/01/android-location-based-services.html 它包含了获取位置的概述。

答案 1 :(得分:0)

使用此

private Location getLocation() {
    // Check that Google Play services is available
    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(this);
    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {
        // In debug mode, log the status
        Log.d("Location Updates", "Google Play services is available.");

        mLocationClient = new LocationClient(this,
                new GooglePlayServicesClient.ConnectionCallbacks() {

                    @Override
                    public void onDisconnected() {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onConnected(Bundle connectionHint) {
                        // TODO Auto-generated method stub
                        mCurrentLocation = mLocationClient
                                .getLastLocation();
                    }
                },
                new GooglePlayServicesClient.OnConnectionFailedListener() {

                    @Override
                    public void onConnectionFailed(ConnectionResult result) {
                        // TODO Auto-generated method stub

                    }
                });
        mLocationClient.connect();
        // Continue
        return mCurrentLocation;
        // Google Play services was not available for some reason
    } else {
        return null;
    }
}

在这里阅读更多内容

http://developer.android.com/training/location/retrieve-current.html