Reputation: 295
I am using GPS location in my app, but when GPS is not enable app crashed. as I am a newbie to android develpment, I googled this and I found this answer in Stackoverflow Check if gps is on In Kitkat (4.4)
The problem here is that PackageUtil & ACCESS_FINE_LOCATION are undefined and I am not sure which library I should download and embed to my app
Any suggestions?
if (PackageUtil.checkPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)) {
Upvotes: 1
Views: 1137
Reputation: 14810
To set a permission in Android, you have to do it in AndroidManifest.xml like this
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
It should be declared after the closing of the <application>
tag.
Read more about it in the docs
UPDATE
You can check whether gps is enabled or not like this
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "GPS is Disabled in your devide", Toast.LENGTH_SHORT).show();
}
And to show the GPS settings page you can use
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
Upvotes: 1
Reputation: 827
First add this permission in the manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Remove the if code you have written.
Then add this GPS checker code. This code checks whether GPS is enabled or not. If it is not enabled it will open the GPS settings.
private void CheckEnableGPS() {
String provider = Settings.Secure.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.equals("")){
//GPS Enabled
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enable GPS"); // GPS not found
builder.setMessage("The app needs GPS to be enabled do you want to enable it in the settings? "); // Want to enable?
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setCancelable(false);
builder.create().show();
return;
}
}
Upvotes: 1