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[]。在那种情况下,我不知道如何发布进度!请帮助我。