通知上的取消按钮可删除通知

时间:2013-12-30 19:52:41

标签: android multithreading notifications android-notifications android-pendingintent

我的通知中包含Progress BarCancel按钮。我使用Thread来增加进度条,取消按钮应该清除通知。

以下是通知

的代码
    remoteViews = new RemoteViews(getPackageName(), R.layout.customnotification);
    Intent intent = new Intent(this, LocationBroadcastReceiver.class);
    intent.putExtra("CancelServiceAndNotification","CancelServiceAndNotification");
    intent.putExtra("ID",1);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(),
       0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    remoteViews.setOnClickPendingIntent(R.id.bCancel, pendingIntent);

使用Thread

递增Progress Bar的代码
     thread = new Thread(new Runnable() {
        @Override
        public void run() {
            int incr;
            for(incr = 0;incr<=100;incr+=10){
                remoteViews.setProgressBar(R.id.progressBar, 100, incr, false);
                if(cancelNotification){

                }
                notificationManager.notify(1,notification);
                try{
                    Thread.sleep(1000);
                }
                catch (Exception e){

                }

            }
            notificationManager.cancel(1);
        }
    });
    thread.start();

在广播接收器中,我正在尝试使用

取消通知
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(ID);

问题在于,当我点击Cancel按钮时,通知会消失一秒钟然后再次出现,可能是由于线程仍在运行。如何从广播Receiver类中销毁线程?如何删除cancel按钮上的通知?

2 个答案:

答案 0 :(得分:3)

要停止线程,您应该中断它,例如当您在BroadcastReceiver中收到“CancelServiceAndNotification”时,您可以致电:

thread.interrupt();

然后,在你的run()方法中:

    if (Thread.currentThread().isInterrupted()) {
        // we were interrupted, should stop immediately
        return;
    }

如果线程在休眠时被中断,它会抛出InterruptedException并清除被中断的旗帜,所以在你的情况下非常重要你在捕捉时run()返回InterruptedException 1}}:

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // we were interrupted, should stop immediately
        return;
    }

您应该以同样的方式取消通知:

// make sure you pass 1 as id here as you use it for notify()
notificationManager.cancel(1);

这应该有效。

但是,强烈建议不要从非主线程更新UI(在调用remoteViews.setProgressBar时从自定义线程执行此操作)。

我建议使用自定义AsyncTaskdoInBackground中执行后台工作(而不是run()方法,并在onProgressUpdate更新通知的进度。
您可以通过调用AsyncTask取消cancel()取消interrupt(),方法与上述{{1}}线程类似。

希望有所帮助。

答案 1 :(得分:0)

@Override
    protected void onPause() 
    {
        // TODO Auto-generated method stub
        super.onPause();
        finish();
    }