Hello i did my notification of download file from web. Code below. I want handle click action on notification, close him and stop AsyncTask job. At current time i have incomprehensible to me actions. Like, when i click on notification its closed him but open again when call publishProgress method of AsyncTask. How i handle click on notification? May be i can do it differently than has? I put button in xml layout and setOnClickListener for call cancel(boolean) method but later learned that it impossible.
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();
}
}
I would imagine something like a broadcast receiver or maybe even an activity or a service being designed to receive the intent fired by the notification click. This entity in turn might be used to cancel the task.
Just call the cancel(true) method on the running Async object.
I hope it helps..