2011-02-24 88 views
1

我在我的服务中收到了一条通知,我在我的onDestroy中取消了该通知。立即在取消代码执行后重新显示通知。任何线索?我试过所有的旗帜组合。没有快乐。为简洁起见编辑的代码在这里。取消后通知重新出现

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); 
     } 
    }; 
+0

你能分享你的代码的相关部分吗?通知何时创建以及何时取消? – 2011-02-24 12:34:49

回答

0

处理程序即使在服务被销毁后仍继续执行,因此处理程序循环中的通知会重新出现。我修改了代码,以便处理程序循环在onDestroy()之后不会继续。我也实现了Handler.Callback,因为它更清洁,而不是内联代码。

@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; 
    }