Android - Check if GPS is enabled

21:46 JPCO 0 Comments



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.




@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();
}
view raw gistfile1.java hosted with ❤ by GitHub

0 comentarios: