我使用java線程從API下載zip文件。當我開始下載文件時,下載進度將顯示在通知欄中。當我向下滾動通知欄時,它沒有響應,只是掛起設備,直到下載完成。如果下載完成,那麼在滾動通知欄中沒有問題。通知欄沒有響應,同時使用java線程下載一個項目android
我的問題是:
1.how,讓應用運行流暢,沒有任何滯後是否有任何其他的方法來處理在安卓下載進度?
2.the app take some time to start download.is there any problem with the code that i am using.
這裏是我的代碼:
protected void doDownload(final String urlLink, final String fileName) {
final Thread dx = new Thread() {
public void run() {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/EriReader/temp/");
if (dir.exists() == false) {
dir.mkdirs();
}
//Save the path as a string value
try {
URL url = new URL(urlLink);
Log.i("FILE_NAME", "File name is " + fileName);
Log.i("FILE_URLLINK", "File URL is " + url);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
final int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(dir + "/" + fileName);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (fileLength > 0) {
int status = ((int) (total * 100/fileLength));
// Notification in notification bar
mBuilder.setProgress(100, status, false);
mNotifyManager.notify(id, mBuilder.build());
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
Log.i("DOWNLOADING err", "ERROR IS" + e);
}
mBuilder.setContentText("Download complete")
// Removes the progress bar
.setProgress(0, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
};
}
使用的AsyncTask,而不是一個線程。 –
但使用異步任務下載較大的文件是不好,我認爲。 –
你已經做了一個線程,線程不用於UI更新,在這裏你總是試圖通知mNotifyManager.notify(id,mBuilder.build());所以通知欄掛起,直到線程停止。 –