Create Notification to download file

 private void downloadFile(String url) { new AsyncTask<String, Integer, File>() { private Exception m_error = null; private static final int NOTIFY_ID = 1; NotificationManager myNotificationManager; Notification notification; Context context; @Override protected void onPreExecute() { myNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); int icon = android.R.drawable.stat_sys_download; CharSequence tickerText = ""; long when = System.currentTimeMillis(); context=getApplicationContext(); notification = new Notification(icon, tickerText, when); Intent notificationIntent = new Intent(context, WebBrawser.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); RemoteViews contentView; contentView = new RemoteViews(getPackageName(), R.layout.notification); contentView.setProgressBar(, 100, 0, false); contentView.setTextViewText(,"FILENAME.mp3"); notification.contentIntent = contentIntent; notification.contentView = contentView; myNotificationManager.notify(NOTIFY_ID, notification); } 

Update ProgressBar

 protected void onProgressUpdate(final Integer... values) { new Thread(new Runnable() { public void run() { Runnable() { public void run() { int progress=(int) ((values[0] / (float) values[1]) * 100); Integer textProgress=new Integer(progress); notification.contentView.setProgressBar(, 100, progress, false); notification.contentView.setTextViewText(, textProgress.toString()+"%"); myNotificationManager.notify(NOTIFY_ID, notification); } }); } }).start(); } 

But at the beginning of the download, the application hangs, I update it in a separate thread. Downloading a file without Notification is done correctly. Help me figure out what I did wrong.

  • why do you create a stream in onProgressUpdate? this handler is executed in the main thread. Try to set the progress directly, without additional flow. - Yura Ivanov
  • I tried the same thing, I thought if the update was carried out in a separate stream, it would be more effective. - ramin

1 answer 1

Found the cause of the hang. The problem was due to multiple calls

 publishProgress(downloadedSize, totalSize); int updateProgressBool=(int) ((downloadedSize/(double)totalSize) * (double)100); if (updateProgressBool >=a) { System.out.println(updateProgressBool); a+=5; previusProgressBool=updateProgressBool; publishProgress(downloadedSize, totalSize); } 

Corrected so that progress is updated every 5% of the downloaded file.