Если вы хотите постоянно проверять, включен ли gps или нет, используйте следующий код:
Шаг 1: Добавьте службу в манифесте
<service android:name=".services.GPSService"
android:enabled="true"
android:exported="true" />
Шаг 2: Ваша служба будет выглядеть так:
public class GPSService extends Service {
private static final String PACKAGE_NAME = GPSService.class.getPackage().getName();
public static final String ACTION_BROADCAST = PACKAGE_NAME + ".broadcast";
public static final String EXTRA_GPS_STATE = PACKAGE_NAME + ".location";
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
public GPSService() {
Log.d(TAG, "GPSService: "); }
private class LocationListener implements android.location.LocationListener{
Location mLastLocation;
public LocationListener(String provider) {
mLastLocation = new Location(provider);
}
@Override
public void onLocationChanged(Location location) {
mLastLocation.set(location);
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Enable gps", Toast.LENGTH_SHORT).show();
// Notify anyone listening for broadcasts about the new gps state.
Intent intent = new Intent(ACTION_BROADCAST);
intent.putExtra(EXTRA_GPS_STATE, provider);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
}
@Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
if (mLocationManager != null) {
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
}
@Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
Шаг 3: Добавьте сервис и широковещательный прием в вашу деятельность:
private GPSStateReceiver gpsStateReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gpsStateReceiver = new GPSStateReceiver();
setContentView(R.layout.activity_home);
}
@Override
protected void onResume() {
super.onResume();
Intent startGPSService = new Intent(this, GPSService.class);
startService(startGPSService);
LocalBroadcastManager.getInstance(this).registerReceiver(gpsStateReceiver,
new IntentFilter(GPSService.ACTION_BROADCAST));
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(gpsStateReceiver);
super.onPause();
}
@Override
protected void onStop() {
stopService(new Intent(this, GPSService.class));
}
/**
* Receiver for broadcasts sent by {@link LocationUpdatesService}.
*/
private class GPSStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//this onReceive method will call when user disable gps
}
}