I have googled this non stop today and could not find anything. My scenario is the following:
I have an Android app that auto replies to incoming messages. I have the below code to create a persistent (non swipe-able) notification and then when the app is destroyed via onDestroy the notification is removed. However, when I open the recents panel and swipe my app away, the app stops the auto reply service and the broadcast receiver stops, however onDestroy is not called and the notification is still visible.
public void notifCreate() {
Intent i = new Intent(Main.this, Main.class);
PendingIntent pi = PendingIntent.getActivity(Main.this, 1, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder notifBuilder = new Notification.Builder(getApplicationContext());
notifBuilder.setContentTitle(getString(R.string.app_name));
notifBuilder.setContentText(getString(R.string.notification));
notifBuilder.setContentIntent(pi);
notifBuilder.setSmallIcon(R.drawable.ic_launcher);
notifBuilder.setOngoing(true);
Notification notif = notifBuilder.getNotification();
notifManager.notify(1, notif);
}
public void notifDestroy() {
NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.cancelAll();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
loadPrefs();
}
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
@Override
protected void onPause() {
super.onPause();
notifCreate();
}
@Override
protected void onResume() {
super.onResume();
loadPrefs();
checkStates();
notifDestroy();
}
@Override
public void onDestroy() {
super.onDestroy();
notifDestroy();
service = false;
}
My goal is the following:
I would love to simply destroy the notification if the app is force closed etc, or if possible I would not mind the app to be a service so even when swiped from the recents, it will still run. The best scenario would be, however, for when my broadcast receiver is running (so somehow detect when it is actually working) and whenever it is on, show a notification. Whenever it is not running the notification should be wiped. If more code is needed etc just comment, thanks for any help guys.