AsycTask跳帧。没有更新UI

时间:2015-09-22 12:56:57

标签: android android-asynctask

我正在使用异步任务从服务器下载文件, 在文件下载期间,我将使用针显示进度。 在异步任务中,我正在调用发布进度方法。

         while (true) {
                        final int read = inputStream.read(readArray);
                        if (read <= 0) {
                        break;
                        }
                       totalRead+= read;
                       this.publishProgress(String.valueOf(100L * totalRead/ contentLength));
                     }

但如上所述

  

onProgressUpdate(Progress ...),在调用后在UI线程上调用   发布进度(进度......)。执行的时间是   未定义。此方法用于显示任何形式的进度   后台计算仍在执行时的用户界面。   例如,它可用于为进度条设置动画或显示登录   文本字段。

它没有更新确切的时间。 我试图通过传递所需的旋转角度值来改变onProgressUpdate方法中的针角度。

 final Matrix matrix = new Matrix();
 matrix.postRotate((float) (rotaionAngle));
 this.needleImage.setImageBitmap(Bitmap
                   .createBitmap(this.pointerBitmap, 0, 0,
                                this.pointerBitmap.getWidth(),
                                this.pointerBitmap.getHeight(),
                                matrix, true));

但是每次都没有执行.frames正在跳过跳过警告即将到来。

  

跳过100帧应用程序可能在其主要上做了太多工作   螺纹

我如何解决这个问题,以免错过GUI中的更新?

2 个答案:

答案 0 :(得分:1)

onProgressUpdate方法中的所有内容都在主线程上。这部分需要太长时间:

Bitmap.createBitmap(
    this.pointerBitmap,
    0, 
    0,
    this.pointerBitmap.getWidth(),
    this.pointerBitmap.getHeight(),
    matrix, 
    true)
);

避免在主线程上执行这样的昂贵操作,而是考虑在异步任务中创建位图。考虑这样的事情:

private class AsyncTaskExample extends AsyncTask<Void, Bitmap, Void>{

        @Override
        protected void onProgressUpdate(Bitmap... values) {
            super.onProgressUpdate(values);

            if(values.length >0){
                needleImage.setImageBitmap(values[0]);
            }


        }

        @Override
        protected Void doInBackground(Void... params) {

            //do some stuff


            final Matrix matrix = new Matrix();
            while (true) {
                final int read = inputStream.read(readArray);
                if (read <= 0) {
                    break;
                }
                totalRead+= read;

                matrix.reset();
                matrix.postRotate(100L * totalRead/ contentLength);

                publishProgress(
                    Bitmap.createBitmap(
                        this.pointerBitmap,        // keep a copy of the bitmap within the asynctask so you can access it 
                        0, 
                        0,
                        this.pointerBitmap.getWidth(),
                        this.pointerBitmap.getHeight(),
                        matrix, 
                        true
                    )
                );
            }

            // do some stuff
            return null
        }
    }
}

但是,除了本主题之外,如果您可以创建自己的绘图而不是一直创建位图的自定义类,您将获得更好的性能。

答案 1 :(得分:1)

每次要显示进度时都不应创建新的位图。尝试改为旋转ImageView。