【发布时间】:2014-02-09 03:22:37
【问题描述】:
我今天不停地用谷歌搜索,但找不到任何东西。我的情况如下:
我有一个自动回复传入消息的 Android 应用。我有下面的代码来创建一个持久(不可滑动)通知,然后当应用程序通过 onDestroy 销毁时,通知被删除。但是,当我打开最近面板并滑动我的应用程序时,应用程序停止自动回复服务并且广播接收器停止,但是没有调用 onDestroy 并且通知仍然可见。
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;
}
我的目标如下:
如果应用程序被强制关闭等,我很想简单地销毁通知,或者如果可能的话,我不介意该应用程序是一项服务,因此即使从最近刷卡,它仍然会运行。但是,最好的情况是,当我的广播接收器正在运行时(因此以某种方式检测它何时实际工作)并且无论何时打开,都会显示通知。每当它不运行时,应该清除通知。如果需要更多代码等,请发表评论,感谢您的帮助。
【问题讨论】:
标签: android notifications