状态栏中的通知,通知关闭时停止asynctask

时间:2011-12-21 17:14:00

标签: android push-notification

您好我从网上发出了下载文件的通知。代码如下。我想在通知上处理点击操作,关闭他并停止AsyncTask工作。目前我对我的行为感到难以理解。就像,当我点击通知时,它关闭了他,但在调用AsyncTask的publishProgress方法时又打开了。我如何处理点击通知?可能我可以做的不同吗?我将按钮放在xml layoutsetOnClickListener中用于调用cancel(boolean)方法,但后来才知道这是不可能的。

public class DownloadFileNotification extends AsyncTask<String, Integer, String> {

public DownloadVkVideoFiles(Context c, String title) {
  //constructor
}

public void createNotification() {
    //create notification
    notificationManager = (NotificationManager) context
            .getSystemService(context.NOTIFICATION_SERVICE);
    Intent notificationIntent = new Intent();

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
            notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    RemoteViews contentView = new RemoteViews(context.getPackageName(),
            R.layout.download_notification);

    // TODO change to shows title
    tickerText = context.getResources().getText(R.string.downloadTitle);
    icon = android.R.drawable.stat_sys_download;
    time = System.currentTimeMillis();

    notification = new Notification(icon, tickerText, time);
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    contentView.setImageViewResource(R.id.downloadImage,
            R.drawable.download);
    contentView.setTextColor(R.id.title, notification_text_color);
    contentView.setFloat(R.id.title, "setTextSize",
            notification_text_size - 3);
    contentView.setTextViewText(R.id.title, title);
    contentView.setProgressBar(R.id.progressBar, 100, 0, false);

    notification.contentIntent = pendingIntent;
    notification.contentView = contentView;
    notificationManager.notify(HELLO_ID, notification);
}

@Override
protected void onPreExecute() {
    // execute the status bar notification
    createNotification();
    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
    //download file
}

@Override
public void onProgressUpdate(Integer... progress) {
    //update progress bar notification
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
  // result processing 
}

@Override
protected void onCancelled() {
    super.onCancelled();
}

}

1 个答案:

答案 0 :(得分:0)

我会想象像广播接收器或者甚至是设计用于接收通知点击触发的意图的活动或服务。反过来,该实体可能会用于取消任务。

只需在正在运行的Async对象上调用cancel(true)方法。

//In your broadcast receiver/ activity / service
sometask.cancel(true);
.
.
.
//Inside doInBackground()
{
    while(!isCancled())
    {
        //continue task
    }
}

我希望它有所帮助..