当前位置失败GoogleMap [英] Current Location failed GoogleMap

查看:244
本文介绍了当前位置失败GoogleMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查GPS是否打开,如果它应显示当前位置。如果不是,它应该要求打开它。如果用户点击取消或不旋转,坐标将被设置为基本。不幸的是总是选择基本的。即使GPS是(我没有得到消息打开GPS)

  @Override 
public void onMapReady (GoogleMap googleMap){
mMap = googleMap;


locationManagerr =(LocationManager)getSystemService(LOCATION_SERVICE);
currentLocation = new Location(location);

if(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED
&&& ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)$ b $ (Build.VERSION.SDK_INT> = Build.VERSION_CODES.M){
requestPermissions(new String [] {Manifest.permission.ACCESS_COARSE_LOCATION,b!= PackageManager.PERMISSION_GRANTED){

if
Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET}
,10);
}
} else
getLocation();
log.i(TAG,latitude+ currentLocation.getLatitude());


private Location getLocation(){

locationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location ){
currentLocation = location;

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

@Override
public void onProviderDisabled(String provider){
AlertDialog.Builder alertDialogBu​​ilder = new AlertDialog.Builder(LocationFinder.this );
alertDialogBu​​ilder.setMessage(GPS关闭,想打开GPS?)
.setCancelable(false)
.setPositiveButton(打开,
新的DialogInterface.OnClickListener (){
public void onClick(DialogInterface dialog,int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBu​​ilder.setNegativeButton(取消,
新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface对话框,int id){
currentLocation = setStartCoordinate();
dialog.cancel();
}
});
AlertDialog alert = alertDialogBu​​ilder.create();
alert.show();
}
};
return currentLocation;
}
私人位置setStartCoordinate(){
位置primaryLocalization = new Location(Basic);
primaryLocalization.setLongitude(0);
primaryLocalization.setLatitude(0);
return primaryLocalization;

$ b @Override
public void onRequestPermissionsResult(int requestCode,@NonNull String [] permissions,@NonNull int [] grantResults){
switch(requestCode){
案例10:
尝试{
getLocation();
log.i(TAG,latitude+ currentLocation.getLatitude());
}
catch(SecurityException ex){log.i(TAG,security error);}
break;
默认值:
break;



$ div $解析方案


这需要大量的案例处理,并且我将通过下面的简要说明提供您请求的所有功能的完整实施。



1。在清单中提供位置权限



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






2。在应用程序的build.gradle中添加位置依赖项



  compile'c​​om.google.android.gms:play-services-location:9.2。 1'






3。扩展BroadcastReceiver并创建GPSStatusReceiver



  public class GPSStatusReceiver extends BroadcastReceiver {
$ b $ private GpsStatusChangeListener mCallback;
private Context mContext;

public GPSStatusReceiver(Context context,GpsStatusChangeListener callback){
mCallback = callback;
mContext = context;

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(android.location.PROVIDERS_CHANGED);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
context.registerReceiver(this,intentFilter);
}

public void unRegisterReceiver(){
Log.d(ali,unRegisterReceiver);
mContext.unregisterReceiver(this);

$ b @Override
public void onReceive(Context context,Intent intent){
if(intent.getAction()。matches(android.location.PROVIDERS_CHANGED )){
Log.d(PROVIDERS_CHANGED中的ali,);
mCallback.onGpsStatusChange();



public interface GpsStatusChangeListener {
void onGpsStatusChange();


$ / code $ / pre

$ hr

4。创建一个类GPSLocation

  public class GPSLocation implements 
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener,
GPSStatusReceiver.GpsStatusChangeListener {

public static final int REQUEST_CHECK_SETTINGS = 100;
public static final int LOCATION_PERMISSION_REQUEST_CODE = 200;

private static final int PERMISSION_GRANTED = 0;
private static final int PERMISSION_DENIED = 1;
private static final int PERMISSION_BLOCKED = 2;

私有GoogleApiClient mGoogleApiClient;
私人位置mCurrentLocation;
private LocationCallback mCallback;
私人活动mActivity;
private Context mContext;
private LocationRequest mLocationRequest;
私人GPSStatusReceiver mGPSStatusReceiver;

private long intervalMillis = 10000;
私人长期最快的InterFontMillis = 5000;
private int accuracy = LocationRequest.PRIORITY_HIGH_ACCURACY;

private boolean isInitialized = false;
private boolean isLocationEnabled = false;
private boolean isPermissionLocked = false;

public GPSLocation(Activity activity,LocationCallback callback){
mActivity = activity;
mContext = activity.getApplicationContext();
mCallback =回调;
if(mGoogleApiClient == null){
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi( LocationServices.API)
.build();
}
createLocationRequest();
mGPSStatusReceiver = new GPSStatusReceiver(mContext,this);
}


public void init(){
isInitialized = true;
if(mGoogleApiClient!= null){
if(mGoogleApiClient.isConnected()){
requestPermission();
} else {
connect();




$ b public void createLocationRequest(){
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(intervalMillis);
mLocationRequest.setFastestInterval(fastestIntervalMillis);
mLocationRequest.setPriority(accuracy);
}


public LocationRequest getLocationRequest(){
return mLocationRequest;


$ b $ public void connect(){
if(mGoogleApiClient!= null&&isInitialized){
mGoogleApiClient.connect();




public void disconnect(){
if(mGoogleApiClient!= null&& isInitialized){
mGoogleApiClient 。断开();




private void getLastKnownLocation(){
if(!mGoogleApiClient.isConnected()){
Log.d( ali,getLastKnownLocation restart);
mGoogleApiClient.connect();
}
else {
if(checkLocationPermission(mContext)&& isLocationEnabled){
Log.d(ali,getLastKnownLocation read);
if(mCurrentLocation == null){
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mCallback.onLastKnowLocationFetch(mCurrentLocation);
}
startLocationUpdates();
} else {
Log.d(ali,getLastKnownLocation get permission);
requestPermission();


Log.d(ali,mCurrentLocation+ mCurrentLocation);


$ b public void startLocationUpdates(){
if(checkLocationPermission(mContext)
&& mGoogleApiClient!= null
& amp ;& mGoogleApiClient.isConnected()
&& isLocationEnabled){
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient,mLocationRequest,this);




public void stopLocationUpdates(){
if(mGoogleApiClient!= null
&& mGoogleApiClient.isConnected )){
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient,this);



$ b @Override
public void onConnected(@Nullable Bundle bundle){
Log.d(ali, onConnected);
requestPermission();



@Override
public void onConnectionSuspended(int i){
Log.d(ali,onConnectionSuspended);


$ b @Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult){
Log.d(ali,onConnectionFailed);


$ b @Override
public void onLocationChanged(Location location){
Log.d(ali,onLocationChanged:+ location) ;
mCallback.onLocationUpdate(location);



@Override
public void onGpsStatusChange(){
Log.d(ali,onGpsStatusChange); (b)如果(isInitialized&&!isPermissionLocked){
if(!isLocationEnabled(mContext)){
isLocationEnabled = false;
isPermissionLocked = true;
stopLocationUpdates();
requestPermission();




$ b private void requestPermission(){
if(ContextCompat.checkSelfPermission(mContext,Manifest.permission.ACCESS_FINE_LOCATION )
!= PackageManager.PERMISSION_GRANTED){
String [] appPerm = new String [] {Manifest.permission.ACCESS_FINE_LOCATION};
ActivityCompat.requestPermissions(mActivity,appPerm,LOCATION_PERMISSION_REQUEST_CODE);
} else {
getLocationSetting();



$ b public void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == GPSLocation.REQUEST_CHECK_SETTINGS){
if(resultCode == Activity.RESULT_OK){
getLastKnownLocation();
} else {
Toast.makeText(mContext,Permission Denied,Toast.LENGTH_SHORT).show();
mCallback.onLocationSettingsError();




$ b private void getLocationSetting(){
LocationSettingsRequest.Builder builder =
new LocationSettingsRequest
.Builder()
.addLocationRequest(mLocationRequest);

PendingResult< LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,builder.build());

result.setResultCallback(new ResultCallback< LocationSettingsResult>(){
@Override
public void onResult(LocationSettingsResult result){
final Status status = result.getStatus );
final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
switch(status.getStatusCode()){
case LocationSettingsStatusCodes.SUCCESS:
Log.d(ali, SUCCESS);
isLocationEnabled = true;
isPermissionLocked = false;
getLastKnownLocation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log。 d(ali,RESOLUTION_REQUIRED);
尝试{
status.startResolutionForResult(
mActivity,
REQUEST_CHECK_SETTINGS);
} catch(IntentSender.SendIntentException e){
e.printStackTrace();
mCallback.onLocationSettingsError();
} finally {
isPermissionLocked = false;
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.d(ali,SETTINGS_CHANGE_UNAVAILABLE);
Toast.makeText(mContext,Location Unavailable,Toast.LENGTH_SHORT).show();
mCallback.onLocationSettingsError();
isPermissionLocked = false;
休息;
}
}
});



$ public void onRequestPermissionsResult(int requestCode,String permissions [],int [] grantResults){
int permState;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:
if(grantResults.length> 0){
if(grantResults [0]!= PackageManager.PERMISSION_GRANTED){$ b $如果(!ActivityCompat.shouldShowRequestPermissionRationale(
mActivity,
Manifest.permission.ACCESS_FINE_LOCATION)){
permState = PERMISSION_BLOCKED;
} else {permState = PERMISSION_DENIED;}
} else {permState = PERMISSION_GRANTED;}
}
else {permState = PERMISSION_DENIED;}

switch permState){
case PERMISSION_BLOCKED:
Toast.makeText(mContext,请给予gps位置权限以使用该应用程序。,Toast.LENGTH_LONG).show();
startInstalledAppDetailsActivity(mContext);
mCallback.onLocationPermissionDenied();
休息;
case PERMISSION_DENIED:
Toast.makeText(mContext,Permission Denied,app can not access the gps location。,Toast.LENGTH_LONG).show();
休息;
case PERMISSION_GRANTED:
getLocationSetting();
休息;
}
break;



public static boolean isLocationEnabled(Context context){
LocationManager locationManager =(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
布尔值gpsEnabled = false;
boolean networkEnabled = false;

尝试{
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex){}

try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex){}

return gpsEnabled&& networkEnabled;
}

public static void startInstalledAppDetailsActivity(final Context context){
if(context == null){
return;
}
final Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse(package:+ context.getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(i);


public static boolean checkLocationPermission(Context context){
String permission =android.permission.ACCESS_FINE_LOCATION;
int res = context.checkCallingOrSelfPermission(permission);
return(res == PackageManager.PERMISSION_GRANTED);
}

public interface LocationCallback {
void onLastKnowLocationFetch(Location location);
void onLocationUpdate(Location location);
void onLocationPermissionDenied();
void onLocationSettingsError();
}


public void close(){
mGPSStatusReceiver.unRegisterReceiver();


$ / code $ / pre

$ hr

5。在活动中使用下面的代码



  public class MainActivity extends AppCompatActivity implements GPSLocation.LocationCallback {

private GPSLocation mGPSLocation;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mGPSLocation = new GPSLocation(this,this);
mGPSLocation.init();

$ b @Override
public void onLastKnowLocationFetch(Location location){
if(location!= null){
Log.d(ali ,onLastKnowLocationFetch+位置);



@Override
public void onLocationUpdate(Location location){
if(location!= null){
Log。 d(ali,onLocationUpdate+位置);



@Override
public void onLocationPermissionDenied(){

}

@Override
public void onLocationSettingsError(){


$ b @Override
protected void onStart(){
mGPSLocation.connect();
super.onStart();
}


@Override
public void onResume(){
super.onResume();
mGPSLocation.startLocationUpdates();
}


@Override
保护无效onPause(){
super.onPause();
mGPSLocation.stopLocationUpdates();
}


@Override
protected void onStop(){
mGPSLocation.disconnect();
super.onStop();
}


@Override
protected void onDestroy(){
mGPSLocation.close();
super.onDestroy();


$ b @Override
public void onRequestPermissionsResult(int requestCode,String permissions [],int [] grantResults){
super.onRequestPermissionsResult(requestCode ,权限,grantResults);
if(requestCode == GPSLocation.LOCATION_PERMISSION_REQUEST_CODE){
mGPSLocation.onRequestPermissionsResult(requestCode,permissions,grantResults);



$ b @Override
public void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult( requestCode,resultCode,data);
if(requestCode == GPSLocation.REQUEST_CHECK_SETTINGS){
mGPSLocation.onActivityResult(requestCode,resultCode,data);
}
}
}


I want to check if the GPS is on if it is should show the current location. If not it should ask to turn it on. If user click cancel or dont turn the coordinates will be set as basic. Unfortunetly allways choose the basic. Even if the GPS is of (i dont get the message to turn on GPS)

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;


    locationManagerr = (LocationManager) getSystemService(LOCATION_SERVICE);
    currentLocation=new Location("location");

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
                    , 10);
        }
    }else
        getLocation();
    log.i(TAG,"latitude  "+currentLocation.getLatitude());
    }

    private Location getLocation(){

                locationListener= new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        currentLocation=location;
                    }

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

                    @Override
                    public void onProviderDisabled(String provider) {
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LocationFinder.this);
                        alertDialogBuilder.setMessage("GPS is off. Want to turn on GPS?")
                                .setCancelable(false)
                                .setPositiveButton("Turn On",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                Intent callGPSSettingIntent = new Intent(
                                                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                                startActivity(callGPSSettingIntent);
                                            }
                                        });
                        alertDialogBuilder.setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                       currentLocation=setStartCoordinate();
                                        dialog.cancel();
                                    }
                                });
                        AlertDialog alert = alertDialogBuilder.create();
                        alert.show();
                    }
                };
       return currentLocation;
        }
    private Location setStartCoordinate(){
        Location primaryLocalization= new Location("Basic");
        primaryLocalization.setLongitude(0);
        primaryLocalization.setLatitude(0);
        return primaryLocalization;
    }

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode){
        case 10:
            try{
                getLocation();
                log.i(TAG,"latitude  "+currentLocation.getLatitude());
            }
            catch (SecurityException ex){log.i(TAG,"security error");}
            break;
        default:
            break;
    }
}

解决方案

This requires a lot of case handling and I am providing a complete implementation of the all the features you requested with brief explanations below.

1. Provide location permission in the manifest

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


2. Add location dependency in app's build.gradle

compile 'com.google.android.gms:play-services-location:9.2.1'


3. extend BroadcastReceiver and create GPSStatusReceiver

public class GPSStatusReceiver extends BroadcastReceiver {

    private GpsStatusChangeListener mCallback;
    private Context mContext;

    public GPSStatusReceiver(Context context, GpsStatusChangeListener callback) {
        mCallback = callback;
        mContext = context;

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.location.PROVIDERS_CHANGED");
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        context.registerReceiver(this, intentFilter);
    }

    public void unRegisterReceiver(){
        Log.d("ali", "unRegisterReceiver");
        mContext.unregisterReceiver(this);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
            Log.d("ali", "in PROVIDERS_CHANGED");
            mCallback.onGpsStatusChange();
        }
    }

    public interface GpsStatusChangeListener{
        void onGpsStatusChange();
    }
}


4. Create a class GPSLocation

public class GPSLocation implements
        ConnectionCallbacks,
        OnConnectionFailedListener,
        LocationListener,
        GPSStatusReceiver.GpsStatusChangeListener {

    public static final int REQUEST_CHECK_SETTINGS = 100;
    public static final int LOCATION_PERMISSION_REQUEST_CODE = 200;

    private static final int PERMISSION_GRANTED = 0;
    private static final int PERMISSION_DENIED = 1;
    private static final int PERMISSION_BLOCKED = 2;

    private GoogleApiClient mGoogleApiClient;
    private Location mCurrentLocation;
    private LocationCallback mCallback;
    private Activity mActivity;
    private Context mContext;
    private LocationRequest mLocationRequest;
    private GPSStatusReceiver mGPSStatusReceiver;

    private long intervalMillis = 10000;
    private long fastestIntervalMillis = 5000;
    private int accuracy = LocationRequest.PRIORITY_HIGH_ACCURACY;

    private boolean isInitialized = false;
    private boolean isLocationEnabled = false;
    private boolean isPermissionLocked = false;

    public GPSLocation(Activity activity, LocationCallback callback) {
        mActivity = activity;
        mContext = activity.getApplicationContext();
        mCallback = callback;
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(mContext)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
        createLocationRequest();
        mGPSStatusReceiver = new GPSStatusReceiver(mContext, this);
    }


    public void init(){
        isInitialized = true;
        if(mGoogleApiClient != null) {
            if (mGoogleApiClient.isConnected()) {
                requestPermission();
            } else {
                connect();
            }
        }
    }


    public void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(intervalMillis);
        mLocationRequest.setFastestInterval(fastestIntervalMillis);
        mLocationRequest.setPriority(accuracy);
    }


    public LocationRequest getLocationRequest() {
        return mLocationRequest;
    }


    public void connect(){
        if(mGoogleApiClient != null && isInitialized) {
            mGoogleApiClient.connect();
        }
    }


    public void disconnect(){
        if(mGoogleApiClient != null && isInitialized) {
            mGoogleApiClient.disconnect();
        }
    }


    private void getLastKnownLocation(){
        if(!mGoogleApiClient.isConnected()){
            Log.d("ali", "getLastKnownLocation restart ");
            mGoogleApiClient.connect();
        }
        else {
            if (checkLocationPermission(mContext) && isLocationEnabled) {
                Log.d("ali", "getLastKnownLocation read ");
                if(mCurrentLocation == null) {
                    mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    mCallback.onLastKnowLocationFetch(mCurrentLocation);
                }
                startLocationUpdates();
            }else{
                Log.d("ali", "getLastKnownLocation get permission ");
                requestPermission();
            }
        }
        Log.d("ali", "mCurrentLocation " + mCurrentLocation);
    }


    public void startLocationUpdates() {
        if(checkLocationPermission(mContext)
                && mGoogleApiClient != null
                && mGoogleApiClient.isConnected()
                && isLocationEnabled) {
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);
        }
    }


    public void stopLocationUpdates() {
        if(mGoogleApiClient != null
                && mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(
                    mGoogleApiClient, this);
        }
    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.d("ali", "onConnected");
        requestPermission();
    }


    @Override
    public void onConnectionSuspended(int i) {
        Log.d("ali", "onConnectionSuspended");
    }


    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d("ali", "onConnectionFailed");
    }


    @Override
    public void onLocationChanged(Location location) {
        Log.d("ali", "onLocationChanged : " + location);
        mCallback.onLocationUpdate(location);
    }


    @Override
    public void onGpsStatusChange() {
        Log.d("ali", "onGpsStatusChange");
        if(isInitialized && !isPermissionLocked) {
            if (!isLocationEnabled(mContext)) {
                isLocationEnabled = false;
                isPermissionLocked = true;
                stopLocationUpdates();
                requestPermission();
            }
        }
    }


    private void requestPermission(){
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED){
            String[] appPerm = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
            ActivityCompat.requestPermissions(mActivity, appPerm, LOCATION_PERMISSION_REQUEST_CODE);
        }else{
            getLocationSetting();
        }
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GPSLocation.REQUEST_CHECK_SETTINGS) {
            if (resultCode == Activity.RESULT_OK) {
                getLastKnownLocation();
            }else{
                Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
                mCallback.onLocationSettingsError();
            }
        }
    }


    private void getLocationSetting(){
        LocationSettingsRequest.Builder builder =
                new LocationSettingsRequest
                        .Builder()
                        .addLocationRequest(mLocationRequest);

        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

        result.setResultCallback(new ResultCallback<LocationSettingsResult>(){
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates locationSettingsStates = result.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        Log.d("ali", "SUCCESS");
                        isLocationEnabled = true;
                        isPermissionLocked = false;
                        getLastKnownLocation();
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        Log.d("ali", "RESOLUTION_REQUIRED");
                        try {
                            status.startResolutionForResult(
                                    mActivity,
                                    REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            e.printStackTrace();
                            mCallback.onLocationSettingsError();
                        }finally {
                            isPermissionLocked = false;
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Log.d("ali", "SETTINGS_CHANGE_UNAVAILABLE");
                        Toast.makeText(mContext, "Location Unavailable", Toast.LENGTH_SHORT).show();
                        mCallback.onLocationSettingsError();
                        isPermissionLocked = false;
                        break;
                }
            }
        });

    }


    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        int permState;
        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0) {
                    if(grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                        if(!ActivityCompat.shouldShowRequestPermissionRationale(
                                mActivity,
                                Manifest.permission.ACCESS_FINE_LOCATION)){
                            permState = PERMISSION_BLOCKED;
                        }else{permState = PERMISSION_DENIED;}
                    }else {permState = PERMISSION_GRANTED;}
                }
                else{permState = PERMISSION_DENIED;}

                switch (permState){
                    case PERMISSION_BLOCKED:
                        Toast.makeText(mContext,"Please give gps location permission to use the app.",Toast.LENGTH_LONG).show();
                        startInstalledAppDetailsActivity(mContext);
                        mCallback.onLocationPermissionDenied();
                        break;
                    case PERMISSION_DENIED:
                        Toast.makeText(mContext,"Permission Denied, app cannot access the gps location.", Toast.LENGTH_LONG).show();
                        break;
                    case PERMISSION_GRANTED:
                        getLocationSetting();
                        break;
                }
                break;
        }
    }

    public static boolean isLocationEnabled(Context context){
        LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        boolean gpsEnabled = false;
        boolean networkEnabled = false;

        try {
            gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch(Exception ex) {}

        try {
            networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch(Exception ex) {}

        return gpsEnabled && networkEnabled;
    }

    public static void startInstalledAppDetailsActivity(final Context context) {
        if (context == null) {
            return;
        }
        final Intent i = new Intent();
        i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        i.addCategory(Intent.CATEGORY_DEFAULT);
        i.setData(Uri.parse("package:" + context.getPackageName()));
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(i);
    }

    public static boolean checkLocationPermission(Context context) {
        String permission = "android.permission.ACCESS_FINE_LOCATION";
        int res = context.checkCallingOrSelfPermission(permission);
        return (res == PackageManager.PERMISSION_GRANTED);
    }

    public interface LocationCallback {
        void onLastKnowLocationFetch(Location location);
        void onLocationUpdate(Location location);
        void onLocationPermissionDenied();
        void onLocationSettingsError();
    }


    public void close() {
        mGPSStatusReceiver.unRegisterReceiver();
    }
}


5. In the activity use the below code

public class MainActivity extends AppCompatActivity implements GPSLocation.LocationCallback {

    private GPSLocation mGPSLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mGPSLocation = new GPSLocation(this, this);
        mGPSLocation.init();
    }

    @Override
    public void onLastKnowLocationFetch(Location location) {
        if(location != null) {
            Log.d("ali ", "onLastKnowLocationFetch " + location);
        }
    }

    @Override
    public void onLocationUpdate(Location location) {
        if(location != null) {
            Log.d("ali ", "onLocationUpdate " + location);
        }
    }

    @Override
    public void onLocationPermissionDenied() {

    }

    @Override
    public void onLocationSettingsError() {

    }

    @Override
    protected void onStart() {
        mGPSLocation.connect();
        super.onStart();
    }


    @Override
    public void onResume() {
        super.onResume();
        mGPSLocation.startLocationUpdates();
    }


    @Override
    protected void onPause() {
        super.onPause();
        mGPSLocation.stopLocationUpdates();
    }


    @Override
    protected void onStop() {
        mGPSLocation.disconnect();
        super.onStop();
    }


    @Override
    protected void onDestroy() {
        mGPSLocation.close();
        super.onDestroy();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == GPSLocation.LOCATION_PERMISSION_REQUEST_CODE) {
            mGPSLocation.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GPSLocation.REQUEST_CHECK_SETTINGS) {
            mGPSLocation.onActivityResult(requestCode, resultCode, data);
        }
    }
}

这篇关于当前位置失败GoogleMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆