强制关闭,用asynctask下载文件

时间:2012-07-05 09:48:19

标签: android android-asynctask

我有一个正在运行的下载功能。但是当我运行它时,就像80%的时间它让我的手机迟钝,强行关闭,没有响应很长时间,如1~2分钟。这种情况非常随机发生,我无法真正追查问题所在。下载完成后,设备将恢复正常。我尝试过各种设备,如galaxy S2,galaxy note,SE xperia Arc S和几张桌子。问题依然存在。任何人都可以建议我如何改进我的代码?以下是我现有的代码:

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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

可能是因为更新UI需要很长时间?也许你可以尝试这样测试,看看它是否有所作为:

@Override
protected void onProgressUpdate(Integer... progress) {          
    Log.d("ANDRO_ASYNC", "Progress: " + progress[0]);
}

顺便说一句,这与你提出的问题无关,但我认为你的代码中存在处理进度的问题:

int progressPercent = (int) ((total*100)/lengthOfFile);
if(progressPercent % 5 == 0){  
     publishProgress(progressPercent);
}

只有当它正好是5,10,15,20%等时才会更新进度...我猜你实际上想要在比之前至少增加%5时更新进度。

int previousProgress = 0;
while ((count = input.read(data)) != -1) {
    total += count;             
    int progressPercent = (int) ((total*100)/lengthOfFile);
    if(progressPercent - previousProgress >= 5) {  
        previousProgress = progressPercent;
        publishProgress(progressPercent);
    }
    output.write(data, 0, count);
}