异步任务下载期间android手机卡住

标签 android android-asynctask

我已经编写了一个代码,可以从 Internet 下载文件。但问题是我的手机会卡住(无响应),直到下载完成。我使用的手机是 Xperia Arc S 和 Galaxy S2。无论如何要解决这个问题?

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.staffchoices);       

        MyI = new Intent(getApplicationContext(), MaxAppsAct.class);
        MyPI = PendingIntent.getActivity(getApplicationContext(), 0, MyI, 0);
        MyNM = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

        Intent intent = new Intent(getApplicationContext(), MaxAppsAct.class);
        final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

        notification = new Notification(R.drawable.logo, "Downloading...", System.currentTimeMillis());
        notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
        notification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.staffchoices);
        notification.contentIntent = pendingIntent;
        notification.contentView.setImageViewResource(R.id.imgIcon, R.drawable.save);
        notification.contentView.setTextViewText(R.id.tvText, "Downloading...");
        notification.contentView.setProgressBar(R.id.pbStatus, 100, progress, false);
        notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
        notificationManager.notify(42, notification);

        String url = "http://www.domainURL.com/3d.png";
        new DownloadFileAsync().execute(url);
        }

        public class DownloadFileAsync extends AsyncTask<String, Integer, Void> {

        @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/3d.png");

                byte data[] = new byte[1024];

                long total = 0;

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

                output.flush();
                output.close();
                input.close();
                } catch (Exception e) {}

            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {          
            notification.contentView.setProgressBar(R.id.pbStatus, 100, progress[0], false);
            notificationManager.notify(42, notification);
            }

        protected void onPostExecute(String unused) {
            notificationManager.cancel(42);

            Notification MyN = new Notification(); MyN.icon = R.drawable.logo1;
            MyN.tickerText = "Download Complete";
            MyN.number = 1;
            MyN.setLatestEventInfo (getApplicationContext(), "Application Title", "Application Description", MyPI);

            MyNM.notify(1, MyN);
        }
    }
}

最佳答案

性能瓶颈似乎是调用 publishProgress 的频率。您应该设计一种方式,在不影响用户体验的情况下减少发布进度的频率。

建议:

  1. 将缓冲区大小增加到合理的值,例如 16K 或 32K
  2. 修改进度发布机制如下:

    while ((count = input.read(data)) != -1) {
        total += count;
        int progressPercent = (int) ((total*100)/lengthOfFile);
        if(progressPercent % 20 == 0){  //publish progress on completion of every 20%
            publishProgress(progressPercent);
        }
        output.write(data, 0, count);
    }
    

关于异步任务下载期间android手机卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11069820/

相关文章:

Android 从 Java 访问 native 屏幕缓冲区

java - Android如何为AsyncTask实现并行执行

java - 使用 AsyncTask 和重启方法

android - 异步任务中的空指针错误

java - Android AsyncTask 保持返回相反的值

android - 如何在 TextView 中启用 'fling scrolling'

java - 如何删除 inputType editText 中的自动填充

android - 我可以在 android 中完全重新启动服务吗?

android - 如何在不使用 WorkManager 立即运行的情况下更改定期工作请求周期?

java - Type enum is not generic 错误克隆和引擎