我有一個正在運行的下載功能。但是當我運行它時,如80%的時間讓我的手機變得遲緩,強行關閉,而不是像1〜2分鐘那樣長時間響應。這個案件發生得非常隨機,我真的無法追查到底是什麼問題。下載完成後,設備將恢復正常。我曾嘗試過各種設備,如星系S2,星系筆記,SE xperia Arc S和幾張桌子。問題依然存在。任何人都可以告訴我如何提高我的代碼?下面是我現有的代碼:強制關閉,使用asynctask下載文件
public void onClickDownload(View view){
String url = "http://www.mydomain.com./" + fileURL;
url = url.replaceAll(" ","%20");
String sourceUrl = url;
new DownloadFileAsync().execute(sourceUrl);
}
public class DownloadFileAsync extends AsyncTask<String, Integer, Void> {
private boolean run_do_in_background = true;
@Override
protected void onPreExecute(){
super.onPreExecute();
}
@Override
protected Void doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lengthOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lengthOfFile);
File folder = new File(Environment.getExternalStorageDirectory() + "/MaxApps");
boolean success = false;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (!success) {
} else {
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/MaxApps/" + apkURL);
byte data[] = new byte[100*1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int progressPercent = (int) ((total*100)/lengthOfFile);
if(progressPercent % 5 == 0){
publishProgress(progressPercent);
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
notificationManager.cancel(Integer.parseInt(ID.toString()));
Notification MyN = new Notification(); MyN.icon = R.drawable.logo1;
MyN.tickerText = "Download Failed";
MyN.number = 1;
MyN.setLatestEventInfo (getApplicationContext(), apkURL + " Download Failed.", "Please try again", MyPI);
MyN.flags |= Notification.FLAG_AUTO_CANCEL;
MyNM.notify(1, MyN);
run_do_in_background = false;
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
notification.contentView.setProgressBar(R.id.pbStatus, 100, progress[0], false);
notificationManager.notify(Integer.parseInt(ID.toString()), notification);
}
@Override
protected void onPostExecute(Void unused) {
if(run_do_in_background) {
notificationManager.cancel(Integer.parseInt(ID.toString()));
Notification MyN = new Notification(); MyN.icon = R.drawable.logo1;
MyN.tickerText = "Download Complete";
MyN.number = 1;
MyN.setLatestEventInfo (getApplicationContext(), "Download Complete, Click to install.", apkURL, MyPI);
MyN.flags |= Notification.FLAG_AUTO_CANCEL;
MyNM.notify(Integer.parseInt(ID.toString()) , MyN);
}
}
}
我不太喜歡你更新onProgressUpdate中的通知,因爲你在UI線程中執行這些操作,然後你以某種方式阻止它。 – rciovati 2012-07-05 10:00:28
你如何創建並執行'DownloadFileAsync'對象? – Caner 2012-07-05 10:04:53
是的,我確實爲通知欄創建了一個新的用戶界面以滿足我的需要,那我該怎麼辦?這是導致問題的原因嗎? @Caner,檢查更新:) – melvintcs 2012-07-05 10:05:07