3

I am using Fused Location Provider API to get device location in my project. When the location services are off it shows an alert dialog asking the user to turn it on.

Is there any way to customize this alert dialog to show a different message?

dialog

Code:

LocationServices.getSettingsClient(this)
            .checkLocationSettings(locationRequestBuilder.build())
            .addOnCompleteListener {
                try { 
                    it.getResult(ApiException::class.java)
                    // Location settings are On
                } catch (exception: ApiException) { // Location settings are Off
                    when (exception.statusCode) {
                        RESOLUTION_REQUIRED -> try { // Check result in onActivityResult
                            val resolvable = exception as ResolvableApiException
                            resolvable.startResolutionForResult(this, LOCATION_REQUEST_CODE)
                        } catch (ignored: IntentSender.SendIntentException) {
                        } catch (ignored: ClassCastException) {
                        } 
                        // Location settings are not available on device
                    }
                }
            }
user158
  • 12,852
  • 7
  • 62
  • 94
hamrosvet
  • 1,178
  • 12
  • 15
  • You cannot change the dialog. It's a google thing. But you can detect if the services are turned off and elect to show a dialog asking user to go to settings and enable it for you (or you can send the user to the settings if you desire to do so). But the dialog is there to prevent malicious apps from silently enabling the location services without user intervention. As far as **I** recall, you cannot turn Location Services from your code, you can -at the very best- send the user to the Settings so she/he can do it on your behalf. – Martin Marconcini Oct 22 '19 at 15:29
  • I have seen apps that can automatically enable location services from a custom alert dialog (the default weather app on Samsung phones for example). – hamrosvet Oct 22 '19 at 15:37
  • I don't have a Samsung device (and I'm glad for it), but if the **default Samsung app** is doing it, **on Samsung phones**, then that's your cue: they can do whatever they want, so as long as they control their hardware and most of their software. Samsung is known to have done many smart and very stupid things on Android. This may as well be something Samsung does. Try the same app o a non Samsung phone. ;-) – Martin Marconcini Oct 22 '19 at 15:39
  • Have you taken a look at [this Stack Overflow question/answer](https://stackoverflow.com/q/33251373/2684) for example? – Martin Marconcini Oct 22 '19 at 15:43
  • I did but it didn't help me do what i wanted so I decided to post this as a separate question. – hamrosvet Oct 22 '19 at 16:49

1 Answers1

0

Try the below line of code

public void checkGpsStatus() {
        try {
            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(30 * 1000);
            locationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);

            PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClientHome,   builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {

                    final Status status = result.getStatus();
                    final LocationSettingsStates state = result.getLocationSettingsStates();

                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.SUCCESS:
                            hideGpsEnablDialog();
                            break;

                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            displayPromptForEnablingGPSSecond(MainActivity.this);
                            break;

                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                            break;
                    }
                }
            });
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Dialog locationDialog;
    public boolean isDialogopen;
    public void displayPromptForEnablingGPSSecond(final Activity activity) {
        if (isDialogopen) {
            return;
        }
        final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
        try {
            locationDialog = new Dialog(activity);
            locationDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            locationDialog.setContentView(R.layout.dialog_confirm_type1);
            locationDialog.setCancelable(false);
            locationDialog.setCanceledOnTouchOutside(false);
            int width = activity.getWindowManager().getDefaultDisplay()
                    .getWidth();
            width = width - 80;
            locationDialog.getWindow().setLayout(width, ActionBar.LayoutParams.WRAP_CONTENT);

            TextView tv_message = (TextView) locationDialog
                    .findViewById(R.id.tv_message);

            tv_message.setText(""+getResources().getString(R.string.gps_enable_message));

            final TextView tv_ok = (TextView) locationDialog
                    .findViewById(R.id.tv_ok);

            final TextView tv_cancel = (TextView) locationDialog
                    .findViewById(R.id.tv_cancel);

            tv_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isDialogopen = false;
                    activity.startActivityForResult(new Intent(action), 11);
                    locationDialog.dismiss();
                }
            });

            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isDialogopen = false;
                    hideGpsEnablDialog();
                }
            });
            locationDialog.show();
            isDialogopen = true;
        } catch (Exception e) {
            ExceptionHandler.printStackTrace(e);
        }
    }

    public void hideGpsEnablDialog() {
        try {
            if (locationDialog != null && locationDialog.isShowing()) {
                locationDialog.dismiss();
            }
            isDialogopen = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

private void turnGPSOn(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(!provider.contains("gps")){ 
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

private void turnGPSOff(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(provider.contains("gps")){
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

Hope it will help for you

gpuser
  • 1,143
  • 1
  • 9
  • 6
  • This method doesn't enable the location services automatically but instead takes the user to settings screen where it has to be enabled manually. Is it possible to turn the location services on directly from the alert dialog itself? – hamrosvet Oct 22 '19 at 15:18
  • yes it is possible to on off the location directly, i have update the above code please check and try. you can use turnGPSOn() method if you want directly – gpuser Oct 22 '19 at 15:42
  • Thanks but it is not working for me (testing on API 26 Oreo). Also, Settings.Secure.LOCATION_PROVIDERS_ALLOWED is deprecated. – hamrosvet Oct 22 '19 at 15:54
  • put this permission and try – gpuser Oct 23 '19 at 06:31