Android:从服务器下载文件,并使用AsyncTask在通知栏中显示下载进度
我使用它从服务器下载文件,使用Android:从服务器下载文件,并使用AsyncTask在通知栏中显示下载进度,android,download,notifications,android-asynctask,Android,Download,Notifications,Android Asynctask,我使用它从服务器下载文件,使用AsycTask,并在通知栏中显示下载进度。我刚刚修改了doInBackground方法,以便下载我的文件: @Override protected Void doInBackground(String... Urls) { //This is where we would do the actual download stuff //for now I'm just going to loop for 10 seconds
AsycTask
,并在通知栏中显示下载进度。我刚刚修改了doInBackground
方法,以便下载我的文件:
@Override
protected Void doInBackground(String... Urls) {
//This is where we would do the actual download stuff
//for now I'm just going to loop for 10 seconds
// publishing progress every second
try {
URL url = new URL(Urls[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100%
// progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream( _context.getFilesDir() + "/file_name.apk");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count ;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
// Create the notification in the statusbar
mNotificationHelper.createNotification();
}
protected void onPostExecute(Void result) {
// The task is complete, tell the status bar about it
mNotificationHelper.completed();
}
protected void onProgressUpdate(Integer... progress) {
// This method runs on the UI thread, it receives progress updates
// from the background thread and publishes them to the status bar
mNotificationHelper.progressUpdate(progress[0]);
}
一切都很顺利,只是我无法拉下通知栏。为什么?您应该覆盖更新UI的方法。以下是从注释中选择的 你能在发表论文之前先用睡眠(1000)法吗 检查。只是猜测 - 是的,它可以工作,但是下载速度变慢了 希望你能理解这个问题。由于您经常更新通知栏,因此无法将其下拉。通过增加数据的块大小,或者每4 kb或更多kb(而不是1kb)更新进度条,可以避免此问题
上述方法不会减慢数据下载速度。我正在这样做:progressUpdate(Integer…progress){//此方法在UI线程上运行,它从后台线程接收进度更新//并将其发布到状态栏mNotificationHelper.progressUpdate(进度[0]);}…但问题是我无法下拉或向上移动通知栏。请发布您的onPreExecute和onPostExecute方法,谢谢。我去看看。您是否在其他设备或模拟器上测试过它?在我看来,这似乎是一个非常奇怪的问题。在不同的设备上测试,总是同一个问题。在发布进度和检查之前,你能不能先输入一个sleep(1000)方法。只是一个猜测。相关问题(也未回答):完全同意。通知进度这么多是没有用的。我可能会使用16kb的缓冲区。