取消后通知会再次出现

时间:2011-02-24 12:23:46

标签: android notifications

我的服务中有通知,我在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);
        }
    };  

1 个答案:

答案 0 :(得分: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;
    }