You can use the below code to check whether gps provider and network providers are enabled or not.
LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
new AlertDialog.Builder(context)
.setMessage(R.string.gps_network_not_enabled)
.setPositiveButton(R.string.open_location_settings, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton(R.string.Cancel,null)
.show();
}
And in the manifest file, you will need to add the following permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Answer from Shankar Agarwal on Stack OverflowYou can use the below code to check whether gps provider and network providers are enabled or not.
LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {}
if(!gps_enabled && !network_enabled) {
// notify user
new AlertDialog.Builder(context)
.setMessage(R.string.gps_network_not_enabled)
.setPositiveButton(R.string.open_location_settings, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton(R.string.Cancel,null)
.show();
}
And in the manifest file, you will need to add the following permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
I use this code for checking:
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}else{
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
The following code check if location is enabled or not. If not enabled it shows alert dialog.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch (Exception ex){}
try{
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){}
if(!gps_enabled && !network_enabled){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
Startup.this.startActivity(myIntent);
}
});
dialog.setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
Is your code working ? But you are asking about when do you need to check GPS ?? It depends on your goal, what your app is responsible for, if it is GPS tracker, you can check it when first activity starts, or if is not major function in your app, you can just notify but continue working.
I have dealt with the same problem of checking GPS, there are two types of GPS providers available in Android Framework now :
- Using Google Play Services (it is recommended to use)
- Using old Location Manager
So I have implemented two strategies for the case when device doesn't have google play services installed.
Base Strategy interface.
public interface BaseLocationStrategy {
void startListeningForLocationChanges(LocationChangesListener locationListener);
void stopListeningForLocationChanges();
void setPeriodicalUpdateEnabled(boolean enable);
void setPeriodicalUpdateTime(long time);
Location getLastLocation();
void initLocationClient();
}
Location change listener interface
public interface LocationChangesListener {
void onLocationChanged(Location location);
void onConnected();
void onConnectionStatusChanged();
void onFailure(String failureMessage);
}
And concrete implementation
public class GooglePlayServiceLocationStrategy implements
BaseLocationStrategy,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private Context mAppContext;
private Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationChangesListener mLocationListener;
private boolean mUpdatePeriodically = false;
private LocationRequest mLocationRequest;
private static GooglePlayServiceLocationStrategy INSTANCE;
// Location updates intervals in sec
private static long UPDATE_INTERVAL = 10000; // 10 sec
private static long FASTEST_INTERVAL = 5000; // 5 sec
private static long DISPLACEMENT = 10; // 10 meters
private GooglePlayServiceLocationStrategy(Context context) {
this.mAppContext = context;
}
@Override
public void startListeningForLocationChanges(LocationChangesListener locationListener) {
this.mLocationListener = locationListener;
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
public void stopListeningForLocationChanges() {
mLocationListener = null;
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
mGoogleApiClient.disconnect();
}
}
public static BaseLocationStrategy getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = new GooglePlayServiceLocationStrategy(context);
INSTANCE.initLocationClient();
}
return INSTANCE;
}
@Override
public void setPeriodicalUpdateEnabled(boolean enable) {
this.mUpdatePeriodically = enable;
}
@Override
public void setPeriodicalUpdateTime(long time) {
UPDATE_INTERVAL = time < FASTEST_INTERVAL ? FASTEST_INTERVAL : time;
}
@Override
public Location getLastLocation() {
return this.mLastLocation;
}
@Override
public void initLocationClient() {
mGoogleApiClient = buildGoogleApiClient();
mLocationRequest = createLocationRequest();
}
protected synchronized GoogleApiClient buildGoogleApiClient() {
return new GoogleApiClient.Builder(mAppContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
@Override
public void onConnected(Bundle bundle) {
mLocationListener.onConnected();
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mUpdatePeriodically) {
startLocationUpdates();
}
}
@Override
public void onConnectionSuspended(int i) {
mLocationListener.onConnectionStatusChanged();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
mLocationListener.onFailure(connectionResult.getErrorMessage());
}
/**
* Starting the location updates
*/
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
/**
* Creating location request object
*/
protected LocationRequest createLocationRequest() {
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(UPDATE_INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setSmallestDisplacement(DISPLACEMENT); // 10 meters
return locationRequest;
}
/**
* Stopping location updates
*/
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
mLocationListener.onLocationChanged(location);
}
}
And finally for old way
public class LocationManagerStrategy implements BaseLocationStrategy, LocationListener {
private Context mAppContext;
private LocationManager mLocationManager;
private Location mLastLocation;
private LocationChangesListener mLocationListener;
private boolean mUpdatePeriodically = false;
private static LocationManagerStrategy INSTANCE;
// Location updates intervals in sec
private static long UPDATE_INTERVAL = 10000; // 10 sec
private static long FASTEST_INTERVAL = 5000; // 5 sec
private static long DISPLACEMENT = 10; // 10 meters
private LocationManagerStrategy(Context context) {
this.mAppContext = context;
}
public static LocationManagerStrategy getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = new LocationManagerStrategy(context);
INSTANCE.initLocationClient();
}
return INSTANCE;
}
@Override
public void startListeningForLocationChanges(LocationChangesListener locationListener) {
mLocationListener = locationListener;
try {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
UPDATE_INTERVAL,
DISPLACEMENT, this);
} catch (SecurityException ex) {
ex.printStackTrace();
}
}
@Override
public void stopListeningForLocationChanges() {
try {
mLocationManager.removeUpdates(this);
} catch (SecurityException ex) {
ex.printStackTrace();
}
}
@Override
public void setPeriodicalUpdateEnabled(boolean enable) {
mUpdatePeriodically = enable;
}
@Override
public void setPeriodicalUpdateTime(long time) {
UPDATE_INTERVAL = time;
}
@Override
public Location getLastLocation() {
if (mLastLocation == null) {
try {
mLastLocation = mLocationManager.getLastKnownLocation(getBestProvider());
} catch (SecurityException securityException) {
return null;
}
}
return mLastLocation;
}
private String getBestProvider() {
Criteria criteria = new Criteria();
return mLocationManager.getBestProvider(criteria, false);
}
@Override
public void initLocationClient() {
mLocationManager = (LocationManager) mAppContext.getSystemService(Context.LOCATION_SERVICE);
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
mLocationListener.onLocationChanged(location);
if (!mUpdatePeriodically) {
this.stopListeningForLocationChanges();
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
mLocationListener.onConnectionStatusChanged();
}
@Override
public void onProviderEnabled(String provider) {
mLocationListener.onConnected();
}
@Override
public void onProviderDisabled(String provider) {
mLocationListener.onFailure(provider);
}
}
check location service is enable or not in android device
gps - Check if 'Access to my location' is enabled - Android - Stack Overflow
Android: Check if Location Services Enabled using Fused Location Provider - Stack Overflow
Android: Checking if google settings location is enabled - Stack Overflow
sorry for asking this but i am not a mobile app developer. we are using mobile device management (mdm) to manage android enterprise mobile device but the mdm did not has the feature to enforce location service to enable in settings app.
i would like to ask how developer code their app if the app requires location service to enable in device level before can use the app? is there such coding way to always check if device location service is on or not when the app is launch to use? if location service is off, a pop-up will prompt user to on it and the app will be shutdown if location service is off until user on it?
Edit 1: the location service at device level i referring to is the below (in red):
You can check it like that:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) // Return a boolean
EDIT:
If you want to check the network provider:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) // Return a boolean
EDIT 2:
If you want to open the settings, you can use this intent:
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
may be this will be useful check this site it discusses about location service
http://www.scotthelme.co.uk/android-location-services/
This android developer training tutorial could help - here's the basics:
Code to run in your Activity onCreate():
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mGoogleApiClient.connect();
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
final LocationSettingsStates LS_state = locationSettingsResult.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
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(LocationByGPS.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// 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 this Method:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
GetUserLocation();//FINALLY YOUR OWN METHOD TO GET YOUR USER LOCATION HERE
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
break;
default:
break;
}
break;
}
}
Remember to Implement these in your class:
public class MyClass extends AppCompatActivity implements
ActivityCompat.OnRequestPermissionsResultCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
/*
your code i.e. with the above code etc....
*/
}
Good explanation here in this Google developer link.
Cheers!
See SettingsApi: check your location request then ensure that the device's system settings are properly configured for the app's location needs.
I thought this is the best solution.
You can check by following code :
/**
* This is used to check whether location is enabled or not.
* @param mContext
* @return
*/
public static boolean isDeviceLocationEnabled(Context mContext) {
int locMode = 0;
String locProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locMode = Settings.Secure.getInt(mContext.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locMode != Settings.Secure.LOCATION_MODE_OFF;
}else{
locProviders = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locProviders);
}
}
There should be one change, where you check TextUtils.isEmpty(locationProviders). It is never empty. Where there is no provider (location settings are disabled) it has value "null". Yes I mean value "null", not null.