2011-12-21 78 views
0

你好,我做了我從網上下載文件的通知。下面的代碼。我想處理通知的點擊操作,關閉他並停止AsyncTask工作。目前,我對自己的行爲感到難以理解。比如,當我點擊通知時,它關閉了他,但是在調用AsyncTask的publishProgress方法時再次打開。我如何處理點擊通知?可能我可以做得比現在有所不同嗎?我把按鈕放在xml layoutsetOnClickListener中撥打電話cancel(boolean)方法,但後來得知它不可能。通知在狀態欄中,當通知關閉時停止asynctask

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(); 
} 

} 

回答

0

我會想像一個廣播接收器,或者甚至是一個活動或服務被設計爲接收通知點擊激發的意圖。這個實體可能會被用來取消任務。

只需在正在運行的Async對象上調用cancel(true)方法即可。

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

我希望它有助於..

+0

只是有趣,爲什麼到處寫使用'while'循環,如果我可以打電話取消,沒有它'asynctask'休息。現在瞭解如何使用服務和廣播。謝謝 – Mrusful 2011-12-23 19:14:03