我目前正在构建一个可以播放声音的应用程序。当用户启动声音时,我会使用以下代码显示状态栏通知:
notificationManager = (NotificationManager) activity.getSystemService(Activity.NOTIFICATION_SERVICE);
Intent intent = new Intent(activity, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);
notification = new Notification();
notification.icon = android.R.drawable.stat_notify_sync;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
String title = activity.getString(R.string.notification_title);
String text = activity.getString(R.string.notification_text);
notification.setLatestEventInfo(activity, title, text, pendingIntent);
这工作正常。稍后,如果用户停止所有声音,我使用 notificationManager.cancel 删除通知,并且再次运行正常。
我的问题是我想处理某人使用任务杀手应用程序的情况。如果有人使用它来杀死我的应用程序,我希望从状态栏中删除通知图标。我知道很多用户喜欢使用此类应用程序,我不希望有人抱怨他们无法“关闭”我的应用程序!
到目前为止,我还无法检测到应用程序何时即将退出。我试过这个:
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
@Override
public void uncaughtException(Thread thread, Throwable ex)
{
notificationManager.cancel(NOTIFICATION_ID);
}
});
还有这个:
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
notificationManager.cancel(NOTIFICATION_ID);
}
});
但这是行不通的。当我的应用程序被终止时,通知图标仍然存在。为了杀死我的应用程序,我一直在使用一个名为“高级任务杀手”的应用程序。我还通过在 DDMS 中终止我的进程进行了测试。
我注意到本机媒体播放器正在这样做。如果正在播放音乐并且您终止了音乐服务,该图标将会消失。
那么,有没有办法检测应用程序何时即将退出,以便我可以删除通知图标?或者如果我的应用程序被终止,有没有办法自动删除通知图标?
Thanks!