Я делаю IntentService, который подключается к веб-службе каждые 15 минут и показывает уведомление. Когда приложение открыто, работа по обслуживанию и уведомление было шоу, но когда близко сервисные работы приложения только в Android API < 21.IntentService не работает в Android Lollipop, когда приложение закрывается
IntentSerice:
public class NotificationsService extends IntentService {
private static final String TAG = "NotificationsService";
public NotificationsService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
ConnectionDetector checkNetwork = new ConnectionDetector(this);
if (!checkNetwork.isNetworkAvailableAndConnected()) {
return;
}
try {
// Connect to web service
} catch (IOException | JSONException e) {
Log.e(TAG, "Error", e);
}
// Show notification
}
public static Intent newIntent(Context context) {
return new Intent(context, NotificationsService.class);
}
public static void setNotificationServiceAlarm(Context context,
boolean isNotificationEnable) {
Intent intent = NotificationsService.newIntent(context);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (isNotificationEnable) {
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_FIFTEEN_MINUTES,
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
}
}
MainActivity:
Button button = (Button) findViewById(R.id.buttonStartService);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
NotificationsService.setNotificationServiceAlarm(this, true);
}
});