Android: 如何修复保存图片时进度条出现延迟的问题

Android: How to fix delay in progress bar showing up when saving image

我有一个按钮,单击它会将位图保存到目录,然后将保存图像的文件路径传递给另一个 activity。但是,在下一个 activity 开始之前,通常会有大约 2 秒的延迟(尤其是位图尺寸较大时)。因此,为了让用户知道在 2 秒的等待时间内正在保存位图,我添加了一个进度条,当单击按钮时它会变得可见。但是,我遇到的问题是进度条不会在单击按钮时立即显示,而是在下一个 activity 开始前几毫秒显示。如何让进度条在点击按钮时立即显示?

下面是与该问题相关的代码片段:

btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                progBar.setVisibility(View.VISIBLE); // show progress bar

                if (progBar.getVisibility() == View.VISIBLE) { // if progress bar is visible


                    Bitmap cropped_image_bitmap = mCropImageView.getCroppedImage(); // uses android-image-cropper library

                    // Save bitmap to directory by calling SaveImage() located in SaveToDirectory.java class
                    //SaveImage() method returns the filepath of image being saved
                    String saved_img_filepath = SaveToDirectory.SaveImage(getApplicationContext(), cropped_image_bitmap);

                    if (saved_img_filepath != null) {
                        //finish(); // ready to end current activity

                        //following are the steps to pass values from current activity to another activity
                        Intent intent = new Intent(getApplicationContext(), ImgpostActivity.class);
                        intent.putExtra("IMAGE_URI", saved_img_filepath);

                        //start next activity
                        startActivity(intent);
                    }

                }


            }
        });

progBar.setVisibility(View.VISIBLE);

肯定是 运行在 UI 线程上,

我猜

Bitmap cropped_image_bitmap = mCropImageView.getCroppedImage(); // uses android-image-cropper library

也是 UI 线程上的 运行,

发生的事情是当你强制显示进度条视图时,ui 重绘阶段需要一些时间,在此之前,你已经调用了另一个命令,如 getCroppedImage,它消耗了所有 UI 线程进度,这就是为什么你遇到屏幕冻结的结果

IMO,如果我的猜测是正确的,解决方案是将 'getCroppedImage()' 移动到辅助线程或匿名线程 (AsnycTask),例如..

new AsyncTask<Void,Void,Void>() {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected Void doInBackground(Void... voids) {
            Bitmap cropped_image_bitmap = mCropImageView.getCroppedImage(); // uses android-image-cropper library
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progBar.setVisibility(View.GONE);
        }
    }