LocationSettingsResult - getStatus未正确检测设置状态

时间:2017-06-17 04:00:43

标签: android gps google-api-client

我已经实现了LocationSettingsResult,以便我的应用程序可以提示用户激活他们的GPS和网络状态。但问题是,在首次启动活动时,即使禁用GPS /网络,getStatus()也始终返回成功,但当活动从后台恢复时,getStatus()能够检测到GPS /网络因此,显示一个对话框,提示用户启用GPS。

这是处理位置事件的类。

public static class LocationHandler {

    private final int INTERVAL = 2000, FAST_INTERVAL = 500;
    OnLocationFoundListener OnLocationFoundListener;
    private GoogleApiClient apiClient;
    private LocationRequest locationRequest;
    private Activity activity;
    private String response = " HI ";

    public LocationHandler(Activity activity) { this.activity = activity; }

    public LocationHandler(Activity activity, OnLocationFoundListener OnLocationFoundListener) {
        this.activity = activity;
        this.OnLocationFoundListener = OnLocationFoundListener;
    }

    public String findLocation() {
        return response;
    }

    public void changeApiState(String state) {

        switch (state){

            case "connect":
                apiClient.connect();
                if (apiClient.isConnecting())
                    Log.d("LocationHandler", "Connecting...");
                break;
            case "disconnect":
                apiClient.disconnect();
                break;
            case "reconnect":
                apiClient.reconnect();
                break;
        }

    }

    public void checkPermission(){

        if(ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {

            ActivityCompat.requestPermissions(activity, new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
            }, Utilities.REQUEST_CODES.LOCATION_REQUEST_CODE);

        }


    }

    private void checkLocationSettingsState(){

        Log.d("LocationHandler", "Checking GPS status");

        LocationSettingsRequest.Builder buildSettingsRequest = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);

        buildSettingsRequest.setAlwaysShow(true);

        PendingResult<LocationSettingsResult> resultPendingResult =
                LocationServices.SettingsApi.checkLocationSettings(
                        apiClient,
                        buildSettingsRequest.build()
                );

        resultPendingResult.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {


                final Status status = locationSettingsResult.getStatus();

                switch (status.getStatusCode()){

                    case LocationSettingsStatusCodes.SUCCESS:
                        Log.d("LocationHander", "Success");
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            Log.d("LocationHandler", "Required");
                            status.startResolutionForResult(activity, REQUEST_CODES.CHECK_SETTING_REQUEST_CODE);
                        } catch (IntentSender.SendIntentException e) {
                            e.printStackTrace();
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Log.d("LocationHandler", "Settings unavailable");
                        break;

                }

            }
        });

    }

    public void buildGoogleClient() {
        Log.d("LocationHandler", "Building client");
        apiClient = new GoogleApiClient.Builder(activity)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(@Nullable Bundle bundle) {
                        Log.d("LocationHandler", "Connected");
                        checkLocationSettingsState();
                    //    setLocationRequest();
                    }

                    @Override
                    public void onConnectionSuspended(int i) {
                        response = "Connection suspended";
                    }
                })
                .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        response = connectionResult.toString();
                    }
                })
                .build();

    }

    private void setLocationRequest() {
        Log.d("LocationHandler", "Requesting location");
        locationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(INTERVAL)
                .setFastestInterval(FAST_INTERVAL);

        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&

                ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(
                apiClient,
                locationRequest,
                new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        Log.d("LocationHandler", "Lat:" + location.getLatitude() + " Lng:" + location.getLongitude());
                        new getLocationName().execute(location.getLatitude(), location.getLongitude());
                        LocationServices.FusedLocationApi.removeLocationUpdates(apiClient, this);
                    }
                }
        );

    }

    class getLocationName extends AsyncTask<Double, Void, Void>{

        @Override
        protected Void doInBackground(Double... params) {

            Log.d("LocationHandler", "Parsing latitude and longitude");
            // params[0] = latitude, params[1] = longitude

            Geocoder getLocationName = new Geocoder(activity, Locale.getDefault());
            List<Address> addresses;
            try {

                addresses = getLocationName.getFromLocation(params[0], params[1], 1);
                Address address = addresses.get(0);
                Log.d("LocationHandler", address.getLocality());
                response = address.getLocality();

            }
            catch (SocketTimeoutException e){
                response = e.getMessage();
                Log.d("LocationHandler", response);
            }
            catch (IOException e) {
                response =  e.getMessage() + "\nHAhahaha";
                Log.d("LocationHandler", response);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            OnLocationFoundListener.onLocationFound(response);
        }
    }

}

这是上课类

的类
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    initComp();
    locationHandler.buildGoogleClient();
    startMostPopularFlipping();
    loadPlacesByType("Home");

}

@Override
protected void onStart() {
    super.onStart();
    locationHandler.changeApiState("connect");
}

我从其他SO那里读到,可能是因为launchMode设置为活动。最初,我的活动设置为singleTask所以我将其更改为标准,但同样的错误发生。

1 个答案:

答案 0 :(得分:0)

试试这个......我正在检查这样的GPS

import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;`
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

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

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

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
            this.canGetLocation = false;
        } else {
            this.canGetLocation = true;
            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 GPS Enabled get lat/long using GPS Services
            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;
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * 
 * @return boolean
 * */
public boolean canGetLocation() {
    // getting GPS status
    locationManager = (LocationManager) mContext
            .getSystemService(LOCATION_SERVICE);
    this.canGetLocation = true;
    isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    // getting network status
    isNetworkEnabled = locationManager
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (!isGPSEnabled && !isNetworkEnabled) {
        this.canGetLocation = false;
    }
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog On pressing Settings button will
 * lauch Settings Options
 * */
public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is 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;
}

}