我使用此example使用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]);
}
除了我无法下拉通知栏外,其他一切都没问题。为什么呢?
答案 0 :(得分:4)
从评论中挑选了以下内容。
请你在publishProgress和之前放一个sleep(1000)方法 校验。只是一个猜测
-
希望你能理解这个问题。由于您经常更新通知栏,因此您无法将其拉下来。通过增加数据的块大小或通过每4个或更多kb而不是1kb更新进度条,可以避免此问题。是的,它有效,但下载速度正在减慢
以上不会减慢数据下载速度。
答案 1 :(得分:2)
您应该覆盖onProgressUpdate方法来更新您的用户界面。