Reputation: 199
i'm trying to close notification when my app being closed,because when i close the app from (Recent Task / Swipe to exit),notification still appear and in case user try to click on notification the app will crash.
@Override
protected void onDestroy() {
super.onDestroy();
notification.cancel(1);
try {
MApplication.sBus.unregister(this);
} catch (Exception e) {
e.printStackTrace();
}
}
in onDestroy()
but doesn't work because onDestroy()
is not called everytime.
Upvotes: 4
Views: 3305
Reputation: 199
problem solved
Add a java class file. Here file name is 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;
}
}
Call this service in your MainActivity oncreate
method.
startService(new Intent(this, KillNotificationService.class));
Add service in Manifest file
<service android:name=".KillNotificationService"/>
Upvotes: 7