Android - Check if GPS is enabled
Here i want to share with you how check if GPS is enabled in android. This utilities is very common when you are developing with google maps.
The snipped code is very simple, if gps is not enabled so it will show a Alert asking you , if you want to enable gps, it's OK a panel of configuration will be opened.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
checkIfGPSEnabled(); | |
} | |
private void checkIfGPSEnabled(){ | |
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); | |
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ | |
showGPSDisabledAlertToUser(); | |
} | |
} | |
private void showGPSDisabledAlertToUser(){ | |
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); | |
alertDialogBuilder.setMessage(getString(R.string.gps_disabled)) | |
.setCancelable(false) | |
.setPositiveButton(getString(R.string.go_gps_setting), | |
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){ | |
dialog.cancel(); | |
} | |
}); | |
AlertDialog alert = alertDialogBuilder.create(); | |
alert.show(); | |
} |
0 comentarios: