LocationSettingsRequest with play-services-location:11.2.0无效。还有其他方法吗?

时间:2017-08-23 19:44:04

标签: android google-play-services google-location-services

我以前使用过LocationSettingsRequest,它的工作方式与预期一致。但是当我将我的播放服务更新为11.2版本时。这对我来说似乎很混乱。首先,此升级意味着不使用 GoogleApiClient ,而不是提供 GeoDataClient PlaceDetectionClient 但是如果我们仍然需要使用 GoogleApiClient 来启用设备位置,那么会留下什么。想到,必须有一些工作,但我还是没有找到。我尝试的代码段如下所示,但无效。

package com.abhishek.testplacesapi;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.abhishek.testplacesapi.utils.Utilities;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.places.GeoDataClient;
import com.google.android.gms.location.places.PlaceDetectionClient;
import com.google.android.gms.location.places.PlaceLikelihood;
import com.google.android.gms.location.places.PlaceLikelihoodBufferResponse;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

public class MainActivity extends AppCompatActivity {

    protected GeoDataClient mGeoDataClient;
    protected PlaceDetectionClient mPlaceDetectionClient;
    // The entry point to the Fused Location Provider.
    private FusedLocationProviderClient mFusedLocationProviderClient;

    private Context mContext;
    protected static final String TAG = "MainActivity";

    private boolean mLocationPermissionGranted;

    // The geographical location where the device is currently located. That is, the last-known
    // location retrieved by the Fused Location Provider.
    private Location mLastKnownLocation;

    /**
     * Constant used in the location settings dialog.
     */
    protected static final int REQUEST_CHECK_SETTINGS = 0x1;

    // Used for selecting the current place.
    private static final int M_MAX_ENTRIES = 5;
    private String[] mLikelyPlaceNames;
    private String[] mLikelyPlaceAddresses;
    private String[] mLikelyPlaceAttributions;
    private LatLng[] mLikelyPlaceLatLngs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        //Construct a GeoDataClient
        mGeoDataClient = Places.getGeoDataClient(this, null);

        //Construct a PlaceDetectionClient api
        mPlaceDetectionClient = Places.getPlaceDetectionClient(this, null);

        // Construct a FusedLocationProviderClient.
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        //Google Api Client

        googleApiClient = new GoogleApiClient
                .Builder(mContext)
                .addApi(LocationServices.API)
                .build();
        googleApiClient.connect();

        //Request Gps Enable
        requestGpsEnable();

    }

    GoogleApiClient googleApiClient;

    private void requestGpsEnable() {


        //Location request
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        //Location Settings Request
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);
        builder.setAlwaysShow(true);

        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(googleApiClient,
                        builder.build());
        Log.i(TAG, ""+result);
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
                final Status status = locationSettingsResult.getStatus();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        Log.i(TAG, "All location settings are satisfied.");
                        if (Build.VERSION.SDK_INT >= 23) {
                            checkLocationRequest();
                        } else {
                            mLocationPermissionGranted = true;
                            getCurrentLocationAddress();
                        }
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        Log.i(TAG, "Location settings are not satisfied. Show the user a dialog " +
                                "to upgrade location settings ");
                        try {
                            // Show the dialog by calling startResolutionForResult(), and check
                            // the result
                            // in onActivityResult().
                            status.startResolutionForResult(MainActivity.this,
                                    REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            Log.i(TAG, "PendingIntent unable to execute request.");
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. " +
                                "Dialog not created.");
                        break;
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // Check for the integer request code originally supplied to startResolutionForResult().
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        Log.i(TAG, "User agreed to make required location settings changes.");
                        //startLocationUpdates();
                        if (Build.VERSION.SDK_INT >= 23) {
                            checkLocationRequest();
                        } else {
                            getCurrentLocationAddress();
                        }
                        break;
                    case Activity.RESULT_CANCELED:
                        Log.i(TAG, "User chose not to make required location settings changes.");
                        break;
                }
                break;
        }
    }

    private static final int LOC_REQ_CODE = 102;

    private void checkLocationRequest() {
        int locationPermissionCheck = ActivityCompat.checkSelfPermission(mContext, Manifest
                .permission.ACCESS_FINE_LOCATION);

        if (locationPermissionCheck != PackageManager.PERMISSION_GRANTED) {
            //Permission not granted
            mLocationPermissionGranted = false;
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission
                    .ACCESS_FINE_LOCATION}, LOC_REQ_CODE);
        } else {
            //Permission granted
            mLocationPermissionGranted = true;
            getCurrentLocationAddress();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mLocationPermissionGranted = false;
        switch (requestCode) {
            case LOC_REQ_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager
                        .PERMISSION_GRANTED) {
                    mLocationPermissionGranted = true;
                    getCurrentLocationAddress();
                } else {
                    mLocationPermissionGranted = false;
                    checkLocationRequest();
                    /*requestGpsEnable();*/
                }
                break;
        }
    }

    private void getCurrentLocationAddress() {
        try{
            Task<PlaceLikelihoodBufferResponse> placeResult = mPlaceDetectionClient.getCurrentPlace(null);

            placeResult.addOnCompleteListener(new OnCompleteListener<PlaceLikelihoodBufferResponse>() {
                @Override
                public void onComplete(@NonNull Task<PlaceLikelihoodBufferResponse> task) {
                    PlaceLikelihoodBufferResponse likelyPlaces = task.getResult();

                    for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                        Log.i("TAG", String.format("Place '%s' has address '%s' likelihood: %g",
                                placeLikelihood.getPlace().getName(),
                                placeLikelihood.getPlace().getAddress(),
                                placeLikelihood.getLikelihood()));
                    }
                    likelyPlaces.release();
                }
            });
        }catch(SecurityException ex){

        }

        /*getCurrentDeviceLocation();*/
        /*showCurrentPlace();*/
    }

    /**
     * Gets the current location of the device.
     */

    private void getCurrentDeviceLocation() {
        try {
            if (mLocationPermissionGranted) {
                Task<Location> locationTask = mFusedLocationProviderClient.getLastLocation();
                locationTask.addOnCompleteListener(this, new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {
                            mLastKnownLocation = task.getResult();
                            Utilities.printLog("" + mLastKnownLocation.getProvider());
                            Utilities.printLog("" + mLastKnownLocation.getLatitude());
                            Utilities.printLog("" + mLastKnownLocation.getLongitude());
                            Utilities.printLog("");
                        } else {

                        }
                    }
                });

            } else {
                checkLocationRequest();
            }
        } catch (SecurityException ex) {
            Log.e("Exception: %s", ex.getMessage());
        }
    }

    /**
     * Show current place
     */

    private void showCurrentPlace() {
        try {
            if (mLocationPermissionGranted) {
                Task<PlaceLikelihoodBufferResponse> placeResult = mPlaceDetectionClient
                        .getCurrentPlace(null);
                placeResult.addOnCompleteListener(this, new
                        OnCompleteListener<PlaceLikelihoodBufferResponse>() {
                            @Override
                            public void onComplete(@NonNull Task<PlaceLikelihoodBufferResponse>
                                                           task) {
                                if (task.isSuccessful() && task.getResult() != null) {
                                    PlaceLikelihoodBufferResponse likelyPlaces = task.getResult();
                                    // Set the count, handling cases where less than 5 entries are
                                    // returned.
                                    int count;
                                    count = likelyPlaces.getCount();
                                    /*if (likelyPlaces.getCount() < M_MAX_ENTRIES) {
                                        count = likelyPlaces.getCount();
                                    } else {
                                        count = M_MAX_ENTRIES;
                                    }*/

                                    int i = 0;
                                    mLikelyPlaceNames = new String[count];
                                    mLikelyPlaceAddresses = new String[count];
                                    mLikelyPlaceAttributions = new String[count];
                                    mLikelyPlaceLatLngs = new LatLng[count];
                                    double prevLikelihood = -0.0;
                                    for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                                        // Build a list of likely places to show the user.
                                        mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace()
                                                .getName();
                                        mLikelyPlaceAddresses[i] = (String) placeLikelihood.getPlace()
                                                .getAddress();
                                        mLikelyPlaceAttributions[i] = (String) placeLikelihood
                                                .getPlace()
                                                .getAttributions();
                                        mLikelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();
                                        i++;
                                        if (i > (count - 1)) {
                                            break;
                                        }
                                    }

                                    // Release the place likelihood buffer, to avoid memory leaks.
                                    likelyPlaces.release();

                                    // Show a dialog offering the user the list of likely places, and
                                    // add a
                                    // marker at the selected place.
                                    /*openPlacesDialog();*/

                                } else {
                                    Log.e(TAG, "Exception: %s", task.getException());
                                }
                            }
                        });
            } else {
                checkLocationRequest();
            }
        } catch (SecurityException ex) {
            Log.e("Exception: %s", ex.getMessage());
        }
    }

}

任何帮助将不胜感激。谢谢你给我宝贵的时间。干杯!!

0 个答案:

没有答案