In Google Maps Android application and many more other applications you had seen that if your Location is disabled then a request location dialog is appearing that directly turn GPS on without redirecting you to Settings page.
To achieve this dialog implementation we have to know below things:
FusedLocationProviderApi
.In this tutorial, we are going to learn how to implement Request Location Dialog with the help of GoogleAPIClient and we will use Broadcast Receiver to check GPS status.
1. Create a new project in Android Studio by navigating to File ⇒ New ⇒ New Project and fill required details. By default my activity is MainActivity.java.
2. Open build.gradle and include this libraries show below:
1 2 3 4 5 |
dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.google.android.gms:play-services:9.0.2' } |
3. Open AndroidManifest.xml and include below permission to it for accessing location.
1 |
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> |
4. Create activity_main.xml and add the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context="com.autolocation_demo.MainActivity"> <!-- TextView to show GPS Status --> <TextView android:id="@+id/gps_status" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="15sp" /> </LinearLayout> |
5. Now follow below steps to implement the functionality.
Step 1: Initiate Google API Client
1 2 3 4 5 6 7 8 |
/* Initiate Google API Client */ private void initGoogleAPIClient() { //Without Google API Client Auto Location Dialog will not work mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } |
Step 2: Now check Location Permission for Marshmallow Devices
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
private void checkPermissions() { if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) requestLocationPermission(); else showSettingDialog(); } else showSettingDialog(); } private void requestLocationPermission() { if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION_INTENT_ID); } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION_INTENT_ID); } } |
Step 3: Method to show Location Dialog when GPS is Off
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
private void showSettingDialog() { LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);//Setting priotity of Location request to high locationRequest.setInterval(30 * 1000); locationRequest.setFastestInterval(5 * 1000);//5 sec Time interval for location update LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(locationRequest); builder.setAlwaysShow(true); //this is the key ingredient to show dialog always when GPS is off 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 state = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: // All location settings are satisfied. The client can initialize location // requests here. updateGPSStatus("GPS is Enabled in your device"); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the user // a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); // Ignore the error. } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way to fix the // settings so we won't show the dialog. break; } } }); } |
Step 4: Getting Result on user action over Location Request Dialog (Yes or No)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
@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 RESULT_OK: Log.e("Settings", "Result OK"); updateGPSStatus("GPS is Enabled in your device"); //startLocationUpdates(); break; case RESULT_CANCELED: Log.e("Settings", "Result Cancel"); updateGPSStatus("GPS is Disabled in your device"); break; } break; } } |
Step 5: Create a Broadcast Receiver to check the status of GPS every time whenever its get On and Off
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
private BroadcastReceiver gpsLocationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //If Action is Location if (intent.getAction().matches(BROADCAST_ACTION)) { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); //Check if GPS is turned ON or OFF if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.e("About GPS", "GPS is Enabled in your device"); updateGPSStatus("GPS is Enabled in your device"); } else { //If GPS turned OFF show Location Dialog new Handler().postDelayed(sendUpdatesToUI, 10); // showSettingDialog(); updateGPSStatus("GPS is Disabled in your device"); Log.e("About GPS", "GPS is Disabled in your device"); } } } }; |
Step 6: Show Location Request Dialog when GPS status Off. Here we have to use Handler to run call the method in Main Thread.
1 2 3 4 5 |
private Runnable sendUpdatesToUI = new Runnable() { public void run() { showSettingDialog(); } }; |
Step 7: Register and Unregister Receiver on onResume and onDestroy method respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Override protected void onResume() { super.onResume(); registerReceiver(gpsLocationReceiver, new IntentFilter(BROADCAST_ACTION));//Register broadcast receiver to check the status of GPS } @Override protected void onDestroy() { super.onDestroy(); //Unregister receiver on destroy if (gpsLocationReceiver != null) unregisterReceiver(gpsLocationReceiver); } |
6. Finally open your MainActivity.java and add the following code to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
package com.autolocation_demo; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.IntentSender; import android.content.pm.PackageManager; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import android.widget.Toast; 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.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.LocationSettingsStates; import com.google.android.gms.location.LocationSettingsStatusCodes; public class MainActivity extends AppCompatActivity { private static final int REQUEST_CHECK_SETTINGS = 0x1; private static GoogleApiClient mGoogleApiClient; private static final int ACCESS_FINE_LOCATION_INTENT_ID = 3; private static final String BROADCAST_ACTION = "android.location.PROVIDERS_CHANGED"; private TextView gps_status; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gps_status = (TextView) findViewById(R.id.gps_status); initGoogleAPIClient();//Init Google API Client checkPermissions();//Check Permission } /* Initiate Google API Client */ private void initGoogleAPIClient() { //Without Google API Client Auto Location Dialog will not work mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } /* Check Location Permission for Marshmallow Devices */ private void checkPermissions() { if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) requestLocationPermission(); else showSettingDialog(); } else showSettingDialog(); } /* Show Popup to access User Permission */ private void requestLocationPermission() { if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION_INTENT_ID); } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION_INTENT_ID); } } /* Show Location Access Dialog */ private void showSettingDialog() { LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);//Setting priotity of Location request to high locationRequest.setInterval(30 * 1000); locationRequest.setFastestInterval(5 * 1000);//5 sec Time interval for location update LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(locationRequest); builder.setAlwaysShow(true); //this is the key ingredient to show dialog always when GPS is off 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 state = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: // All location settings are satisfied. The client can initialize location // requests here. updateGPSStatus("GPS is Enabled in your device"); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the user // a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); // Ignore the error. } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way to fix the // settings so we won't show the dialog. 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 RESULT_OK: Log.e("Settings", "Result OK"); updateGPSStatus("GPS is Enabled in your device"); //startLocationUpdates(); break; case RESULT_CANCELED: Log.e("Settings", "Result Cancel"); updateGPSStatus("GPS is Disabled in your device"); break; } break; } } @Override protected void onResume() { super.onResume(); registerReceiver(gpsLocationReceiver, new IntentFilter(BROADCAST_ACTION));//Register broadcast receiver to check the status of GPS } @Override protected void onDestroy() { super.onDestroy(); //Unregister receiver on destroy if (gpsLocationReceiver != null) unregisterReceiver(gpsLocationReceiver); } //Run on UI private Runnable sendUpdatesToUI = new Runnable() { public void run() { showSettingDialog(); } }; /* Broadcast receiver to check status of GPS */ private BroadcastReceiver gpsLocationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //If Action is Location if (intent.getAction().matches(BROADCAST_ACTION)) { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); //Check if GPS is turned ON or OFF if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.e("About GPS", "GPS is Enabled in your device"); updateGPSStatus("GPS is Enabled in your device"); } else { //If GPS turned OFF show Location Dialog new Handler().postDelayed(sendUpdatesToUI, 10); // showSettingDialog(); updateGPSStatus("GPS is Disabled in your device"); Log.e("About GPS", "GPS is Disabled in your device"); } } } }; //Method to update GPS status text private void updateGPSStatus(String status) { gps_status.setText(status); } /* On Request permission method to check the permisison is granted or not for Marshmallow+ Devices */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case ACCESS_FINE_LOCATION_INTENT_ID: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //If permission granted show location dialog if APIClient is not null if (mGoogleApiClient == null) { initGoogleAPIClient(); showSettingDialog(); } else showSettingDialog(); } else { updateGPSStatus("Location Permission denied."); Toast.makeText(MainActivity.this, "Location Permission denied.", Toast.LENGTH_SHORT).show(); // permission denied, boo! Disable the // functionality that depends on this permission. } return; } } } } |
7. Finally, all done run your code.
Thanks. 🙂
Subscribe to us and get the latest news.
3 Comments
Kyrylo
Monday, July 10th, 2017Thank you very much for this great tutorial! You’ve saved a lot of my nerves! Perfect!
Vivek Solanki
Friday, September 1st, 2017Thank you , Buddy! It helped a lot ^_^
Shahnawaz
Saturday, November 21st, 2020Tutorial was Great and worked.