ali*_*ali 4 java notifications android android-ondestroy
我试图在我的应用程序关闭时关闭通知,因为当我从(最近的任务/滑动退出)关闭应用程序时,通知仍然出现,如果用户尝试单击通知,应用程序将崩溃。
@Override
protected void onDestroy() {
super.onDestroy();
notification.cancel(1);
try {
MApplication.sBus.unregister(this);
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
inonDestroy()但不起作用,因为onDestroy()不是每次都调用。
问题解决了
添加一个java类文件。这里的文件名是KillNotificationService.java
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
public class KillNotificationService extends Service{
@Override
public void onTaskRemoved(Intent rootIntent) {
//Toast.makeText(this, “service called: “, Toast.LENGTH_LONG).show();
super.onTaskRemoved(rootIntent);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) getSystemService(ns);
nMgr.cancelAll();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
在您的MainActivity oncreate方法中调用此服务。
startService(new Intent(this, KillNotificationService.class));
Run Code Online (Sandbox Code Playgroud)
在清单文件中添加服务
<service android:name=".KillNotificationService"/>
Run Code Online (Sandbox Code Playgroud)