0
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);

            }
    }

我写了这段代码来下载一个 mp3 文件,这里的问题是,它没有更新下载文件的进度!我正在使用 IOUtils 类将 InputStream 转换为 byte[]。在那种情况下,我不知道如何发布进度!请帮助我。

4

3 回答 3

2

您需要在 doInBackground() 中调用 publishProgress(param)

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

  1. doInBackground(Params...),在 onPreExecute() 完成执行后立即在后台线程上调用。此步骤用于执行可能需要很长时间的后台计算。异步任务的参数传递到这一步。计算的结果必须由这一步返回,并将传递回最后一步。此步骤还可以使用 publishProgress(Progress...) 来发布一个或多个进度单位。这些值在 UI 线程上的 onProgressUpdate(Progress...) 步骤中发布。

  2. onProgressUpdate(Progress...),在调用 publishProgress(Progress...) 后在 UI 线程上调用。执行的时间是不确定的。此方法用于在后台计算仍在执行时在用户界面中显示任何形式的进度。例如,它可用于动画进度条或在文本字段中显示日志。

一个例子@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);
        }
于 2013-04-10T19:20:39.070 回答
0

AsyncTask的所有函数都有访问说明符protected

所以应该是:

@Override
     protected void onProgressUpdate(Long... progress) {
            super.onProgressUpdate(progress);
            contentText = progress[0] + "% complete";
            notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
            notificationManager.notify(ID, notification);
     }
于 2013-04-10T19:31:17.407 回答
0

我认为没有办法IOUtils.toByteArray(..)提供进度更新。如果文件很大,您可能不想将整个内容读入内存。您可以使用CountingInputStream来跟踪读取的总字节数。

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);
  }
}
于 2013-04-10T19:36:53.660 回答