Question

private class DownloadTextTask extends AsyncTask<String,Long,Long> {

        CharSequence contentText;
        Context context;
        CharSequence contentTitle;
        PendingIntent contentIntent;
        int ID = 1;
        long time;
        int icon;
        CharSequence tickerText;

        @Override
        protected Long doInBackground(String... urls) {
            InputStream inputStream = null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse httpResponse = httpclient.execute(new HttpGet(urls[0]));
                inputStream = httpResponse.getEntity().getContent();
                byte[] buffer = IOUtils.toByteArray(inputStream);
                FileOutputStream fos = new FileOutputStream(MEDIA_PATH + "/fileName.mp3");
                fos.write(buffer);
                fos.flush();
                fos.close();    
            } catch (Exception e) {
            }
            return (long) 100;
        }

        @Override
        protected void onPostExecute(Long result) {
            contentText = result + "% complete";
            contentTitle="Downloading Finished!";
            notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
            notificationManager.notify(ID, notification);
        }

        @Override
         protected void onPreExecute() {
                super.onPreExecute();
                downloadNotification();
         }

         @Override
         public void onProgressUpdate(Long... progress) {
                super.onProgressUpdate(progress);
                contentText = progress[0] + "% complete";
                notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
                notificationManager.notify(ID, notification);
         }

           public void downloadNotification(){
                String ns = Context.NOTIFICATION_SERVICE;
                notificationManager = (NotificationManager) getSystemService(ns);

                icon = R.drawable.downicon;
                //the text that appears first on the status bar
                tickerText = "Downloading...";
                time = System.currentTimeMillis();

                notification = new Notification(icon, tickerText, time);

                context = getApplicationContext();
                //the bold font
                contentTitle = "Your download is in progress";
                //the text that needs to change
                contentText = "0% complete";
                Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
               // notificationIntent.setType("audio/*");
                contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);

                notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
                notificationManager.notify(ID, notification);

            }
    }

I've written this code to download a mp3 file, the problem here is that, its not updating the progress of downloading a file! I'm using IOUtils class for converting InputStream to byte[]. I don't know how to publish progress in that case! Kindly help me.

Was it helpful?

Solution 2

I don't think there is a way for IOUtils.toByteArray(..) to provide a progress update. If the file is large you probably don't want to read the whole thing into memory anyway. You could use CountingInputStream to track the total bytes read.

public long countContent(URL urls) {
  try {
     //...
     CountingInputStream counter = new CountingInputStream(httpResponse.getEntity().getContent());
     FileOutputStream os = new FileOutputStream(MEDIA_PATH + "/fileName.mp3");

     int read;
     byte[] buffer = new byte[1028];
     while ((read = counter.read(buffer)) != -1) {
        os.write(buffer, 0, read);
        publishProgress(counter.getByteCount()/size);
     }
     // ...
     return counter.getByteCount()/size;
  } catch (IOException ex) {
     throw new RuntimeException(ex);
  }
}

OTHER TIPS

You need to call publishProgress(param) in doInBackground()

http://developer.android.com/reference/android/os/AsyncTask.html

  1. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

  2. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

An example @ http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/

        OutputStream output = new FileOutputStream("/sdcard/file_name.extension")
        long total = 0;
        int count;
        while ((count = inputStream.read(buffer) != -1) {
            total += count;
            // publishing the progress....
            publishProgress((int) (total * 100 / fileLength));
            output.write(buffer, 0, count);
        }

All functions of the AsyncTask have the access specifier protected.

So it should be:

@Override
     protected void onProgressUpdate(Long... progress) {
            super.onProgressUpdate(progress);
            contentText = progress[0] + "% complete";
            notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
            notificationManager.notify(ID, notification);
     }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top