Notification reappears after cancellation
I have a notification in my service which I cancel in my onDestroy. The notification immediately reappears after cancel code ex开发者_如何学Pythonecutes. Any clues?. I have tried all the flags combinations. No joy. Code edited for brevity is here.
public class downservice extends Service{
Notification notification;
RemoteViews contentView;
private static final int notifyid = 1;
Context context;
NotificationManager mNM;
PendingIntent cintent;
@Override
public void onCreate() {
String ns = Context.NOTIFICATION_SERVICE;
mNM = (NotificationManager)getSystemService(ns);
Intent noteintent = new Intent(this, configact.class);
cintent = PendingIntent.getActivity(this, 0, noteintent, 0);
contentView= new RemoteViews(getPackageName(), R.layout.notify);
Message msgtx=Message.obtain();
handler.sendMessage(msgtx);
}
private void showNotification(long[] data) {
notification= new Notification();
notification.contentIntent = cintent;
notification.icon=R.drawable.notify;
notification.iconLevel=x;
notification.flags|=Notification.FLAG_AUTO_CANCEL;
contentView.setImageViewResource(R.id.notifyimage, R.drawable.notifyimage);
contentView.setTextViewText(R.id.notifytext,text);
notification.contentView = contentView;
// We use a layout id because it is a unique number. We use it later to cancel.
mNM.notify(notifyid, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onDestroy() {
mNM.cancel(notifyid);
}
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg){
Message msgtx=Message.obtain();
msgtx.arg1=1;
long [] data=getdata();
showNotification(data);
handler.sendMessageDelayed(msgtx, updaterate*1000);
}
};
The handler continues to execute even after service is destroyed and hence the notification which is in the handler loop reappears. I modified the code so that the handler loop does not continue after onDestroy(). I also implemented Handler.Callback since it is cleaner rather than the inline code.
@Override
public boolean handleMessage(Message arg0) {
switch(arg0.arg1){
case 1:
Message msgtx=Message.obtain();
msgtx.arg1=loopstatus;
long [] data=getdata();
showNotification(data);
handler.sendMessageDelayed(msgtx, updaterate*1000);
break;
case 2:
mNM.cancel(notifyid);
break;
default:
break;
}
return true;
}
精彩评论