Используйте широковещательный приемник, чтобы получать включенные или отключенные события gps, а затем транслировать это событие внутри приложения с помощью внутреннего широковещательного приемника.
Это ваш широковещательный приемник, который будет прослушивать события gps.
public class LocationStateChangeBroadcastReceiver extends BroadcastReceiver
{
public static final String GPS_CHANGE_ACTION = "com.android.broadcast_listeners.LocationChangeReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null && intent.getAction().equals(context.getString(R.string.location_change_receiver))) {
if (!isGpsEnabled(context)) {
sendInternalBroadcast(context, "Gps Disabled");
}
}
}
private void sendInternalBroadcast(Context context, String status) {
try {
Intent intent = new Intent();
intent.putExtra("Gps_state", status);
intent.setAction(GPS_CHANGE_ACTION);
context.sendBroadcast(intent);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static boolean isGpsEnabled(Context context) {
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
}
Создание класса внутреннего приемника вещания для получения событий.
class InternalLocationChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// this method will be called on gps disabled
// call openGpsWindow here
}
}
Теперь скопируйте этот код в своей деятельности для регистрации приемников вещания.
public class MainActivity extends AppCompatActivity {
InternalLocationChangeReceiver internalLocationChangeReceiver = new
InternalLocationChangeReceiver();
LocationStateChangeBroadcastReceiver locationStateChangeBroadcastReceiver = new LocationStateChangeBroadcastReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
registerReceiver(locationStateChangeBroadcastReceiver, new IntentFilter("android.location.PROVIDERS_CHANGED"));
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(LocationStateChangeBroadcastReceiver.GPS_CHANGE_ACTION);
registerReceiver(internalLocationChangeReceiver, intentFilter);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(locationStateChangeBroadcastReceiver);
unregisterReceiver(internalLocationChangeReceiver);
}
}