Wednesday, January 22, 2014

Enable GPS Dialog


Below Code display a dilog to enable gps if it is turned off



public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getGPSInfo();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

private void getGPSInfo() {
Criteria criteria = new Criteria();
String provider;
Location location;
LocationManager locationmanager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);

if (locationmanager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
provider = locationmanager.getBestProvider(criteria, false);
location = locationmanager.getLastKnownLocation(provider);

} else {
showGPSDisabledAlertToUser();
}
}


private void showGPSDisabledAlertToUser() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder
.setMessage(
"GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
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();
}// ;

}

You need to put following permissions in your manifestfile


<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>