我正在從服務器上下載視頻。我在通知中顯示下載的進度。一旦下載完成,我會在我的通知中顯示下載完成,但也會看到顯示進度的通知。如何擺脫顯示進度的通知,一旦下載complete.Here是我的代碼AsyncTask生成兩個通知
public class VideoAsyncTask extends AsyncTask<Object, Integer, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
notificationManager = (NotificationManager)
getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("Download in progress")
// .setContentIntent(contentIntent(getApplicationContext()))
.setAutoCancel(true);
notificationBuilder.setProgress(100, 0, false);
notificationManager.notify(1, notificationBuilder.build());
}
@Override
protected void onProgressUpdate(Integer... values) {
notificationBuilder.setProgress(100, values[0], false);
notificationManager.notify(id, notificationBuilder.build());
super.onProgressUpdate(values);
}
@Override
protected Void doInBackground(Object... params) {
try {
URL url = new URL(params[0].toString());
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
String PATH = Environment.getExternalStorageDirectory().toString();
File file = new File(PATH + "/SavedVideos");
try {
file.mkdirs();
} catch (Exception e) {
}
if (!contacts.getVideoName().contains(".mp4")) {
contacts.getVideoName().concat(".mp4");
}
File outputFile = new File(file, contacts.getVideoName());
if (!outputFile.exists()) {
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
publishProgress(Math.min(buffer.length, 100));
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
/* for (int i = 0; i <= 100; i += 5) {
// Sets the progress indicator completion percentage
publishProgress(Math.min(i, 100));
try {
// Sleep for 5 seconds
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
Log.d("Failure", "sleeping failure");
}
}*/
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
notificationBuilder.setContentText("Download Finished");
notificationBuilder.setProgress(0, 0, false);
notificationManager.notify(1, notificationBuilder.build());
}
}
使用ID –
notificationManager.cancel(NOTIFICATION_ID)取消正在進行的通知; –
我在下載時看到兩個通知。當下載完成時,它工作正常 – Pritish