Turn GPS on programmatically like Ola Cabs Android app

前端 未结 7 880
忘了有多久
忘了有多久 2021-02-04 15:44

I am working on an application and need to integrate GPS location. I want to switch the GPS on programmatically. The condition is: I don\'t want to send the user to the Setting

7条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 16:23

    Since SettingsApi is deprecated and after checking into the developer site here. I was able to achive the same result as Ola app.

    Add the below method in your Activity class

    private void switchOnGPS() {
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY));
    
        Task task = LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
        task.addOnCompleteListener(new OnCompleteListener() {
            @Override
            public void onComplete(@NonNull Task task) {
                try {
                    LocationSettingsResponse response = task.getResult(ApiException.class);
                } catch (ApiException e) {
                    switch (e.getStatusCode())
                    {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED :
                            ResolvableApiException   resolvableApiException = (ResolvableApiException) e;
                            try {
                                resolvableApiException.startResolutionForResult(MainActivity.this,REQUEST_CHECK_SETTINGS);
                            } catch (IntentSender.SendIntentException e1) {
                                e1.printStackTrace();
                            }
                            break;
    
                            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                                //open setting and switch on GPS manually
                                break;
                    }
                }
            }
        });
        //Give permission to access GPS
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 11);
    }
    

    Call the above method in your Activity's onResume method like below

    @Override
    protected void onResume() {
        super.onResume();
        switchOnGPS();
    }
    

    Add respective Location permission in Manifest file.

提交回复
热议问题