简体   繁体   中英

Android GPS location services

I have an android application that will track a users location. It is set so it will use Wifi/Network location services if possible else GPS_PROVIDER services. When there is a wifi connection it works perfectly but when I set to only get location from GPS the app crashes. From testing I have the line location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); isn't actually setting the location but rather it is still null. Anyone know why this is happening?

 package temp;

    import android.app.AlertDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.location.Address;
    import android.location.Geocoder;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.content.DialogInterface;
    import android.provider.Settings;
    import android.util.Log;

    import java.util.List;
    import java.util.Locale;

    public class GPSTracker implements LocationListener {
    private Context context;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled;
    Location location;
    boolean canGetLocation = false;
    Geocoder geocoder;
    List<Address> addresses;

    double latitude;
    double longitude;

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
    private static  final long MIN_TIME_BW_UPDATES = 5 * 1000;

    protected LocationManager locationManager;

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

    public Location getLocation(){
        try{
            locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if(!isGPSEnabled && !isNetworkEnabled){
                showSettingsAlert();
            }else{
                this.canGetLocation = true;
                if(isNetworkEnabled) {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();

                            geocoder = new Geocoder(context, Locale.getDefault());
                            this.addresses = geocoder.getFromLocation(latitude, longitude, 1);
                        }
                    }
                }else{
                    Log.e("GPS_Provider: ", "Made it");
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    if(locationManager == null){
                        Log.e("GPS_Provider: ", "Manager1");
                    }else{
                        Log.e("GPS_Provider: ", "Manager2");
                    }

                    if(locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                        if(location == null){
                            Log.e("GPS_Provider: ", "Made it2");
                        }else{
                            Log.e("GPS_Provider: ", "Made it3");
                        }

                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();

                            Log.e("Cords: ", "latitude: " + latitude + " longitude: " + longitude);

                            geocoder = new Geocoder(context, Locale.getDefault());
                            this.addresses = geocoder.getFromLocation(latitude, longitude, 1);
                        }
                    }
                }
            }

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

    public void stopUsingGps(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    public List<Address> getAddress(){
        return this.addresses;
    }

    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
        return  latitude;
    }

    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
        return longitude;
    }

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

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

        alertDialog.setTitle("GPS is settings");
        alertDialog.setMessage("GPS is not enabled.");
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                context.startActivity(intent);
            }
        });

        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        alertDialog.show();

    }

    @Override
    public void onLocationChanged(Location location) {

    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
    }

manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="temp" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".login"
            android:label="@string/title_activity_login" >
        </activity>
        <activity
            android:name=".Register"
            android:label="@string/title_activity_register" >
        </activity>
    </application>

</manifest>

You are getting null as a return because if the GPS never actually obtained a last location it would have nothing to give you

Instead of LocationManager and managing connectivity issues yourself look into the FusedLocationProviderAPI which draws on the most power efficient method of Location polling available and does all that background work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM