【问题标题】:Running FileOutputStream operations in AsyncTask's doInBackground() method does not execute successfully在 AsyncTask 的 doInBackground() 方法中运行 FileOutputStream 操作未成功执行
【发布时间】:2015-11-29 20:50:18
【问题描述】:

我使用 AsyncTask 作为内部类来保存位图。但是 FileOutputStream 操作不起作用。如果我在 UI 线程中的方法中运行相同的代码,则代码运行并且我能够成功保存位图。

我知道 doInBackground() 方法确实会执行,并且 onPostExecute() 方法也会被执行。

另外,如果我获取传递给 AsyncTask 的输入流,并尝试对其进行解码以设置 imageView,则它不起作用。但是,如果我在 AsyncTask 之外使用相同的代码,它就可以工作。

我按如下方式实现了 AsyncTask,第二条和第三条日志语句没有被记录,所以我知道有些东西运行不正常:

public class SaveImageToInternalStorage extends AsyncTask {

    InputStream bitmap;
    String PICTURE_KEY;

    public SaveImageToInternalStorage1(final InputStream bitmap, final String PICTURE_KEY) {
        this.bitmap = bitmap;
        this.PICTURE_KEY = PICTURE_KEY;



      }


        @Override
        protected Object doInBackground(Object[] params) {
            FileOutputStream fos;
            try {

                fos =  picture_chooser.this.openFileOutput(PICTURE_KEY, MODE_PRIVATE);

              Bitmap bitmap2 = BitmapFactory.decodeStream(bitmap);
                Log.v("saveBitmap", " first log statement");  ////This gets logged
                bitmap2.compress(Bitmap.CompressFormat.WEBP, 85, fos);
                 Log.v("saveBitmap", " second log statement");  // This is not logged
                fos.close();

              Log.v("saveBitmap", " third log statement"); // This is not logged
            } catch (Exception e) {
                Log.e("saveToInternalStorage()", e.getMessage());

            }

            return null;
        }


        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
   Log.v("saveBitmap", " onPostExecute log statement");  // This is logged
            imageViewSetter(bitmap);

        }
    }


    //runs in the wrapper class 
      public void imageViewSetter(InputStream inputStream) {
            imageView.setImageBitmap(BitmapFactory.decodeStream(inputStream)); //this does not set the imageView 

        }

任何帮助将不胜感激。

【问题讨论】:

    标签: java android bitmap android-asynctask fileoutputstream


    【解决方案1】:

    看看这个来自Android参考here的例子

    我在下面为你重新创建了代码

     private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }
    
     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }
    
     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
    }
    

    注意顶部的类声明后面是

    <URL, Integer, Long> 
    

    接下来,查看类中的三个重写方法中的每一个。您会注意到 URL 是指传递给 doInBackground 的参数,Integer 是 onProgressUpdate 输出的内容,Long 是您的 doInBackground 方法返回给 onPostExecute 的内容

    从这里你可以希望看到 AsyncTask 应该按如下方式使用

    doInBackground - 传入你想做的任何工作。此方法在后台线程上执行您想要的工作。此方法需要将完成的对象返回到onPostExecute,您可以在此处捕获已完成工作的结果并根据需要更新 UI。 onProgressUpdate 是可选的,你不需要在这里做任何事情。

    【讨论】:

    • 感谢您的详细回复!因此,我将类声明更改为:** extends AsyncTask **,并将 doInBackground() 声明更改为:** protected FileOutputStream doInBackground(FileOutputStream[] params) **,并使用 doInBackground( ) 方法返回 FileOutputStream,但第二和第三条日志语句仍未执行,位图仍未保存。这就是我应该改变的全部吗?再次感谢。
    • Ivan,抛开参数和返回类型,你明白为什么FileOutputStream在第一个log语句之后就停止运行了吗?在这种情况下,通过 AsyncTask 返回位图对我来说不太重要。感谢您的帮助。
    • 我能问一下你想在这里实现什么吗?我可以看到您想要保存图像但在整个应用程序的更广泛的上下文中?我或许可以提出一种替代方法。
    • 嗨,Ivan,抱歉回复晚了。此任务的主要目的是保存从图库中获取的图像。该任务是用户为其用户配置文件选择他们想要的图片的活动的一部分。我需要这些图像在不同的活动中可用。选择的每张照片都会填充一个 ImageButton,用户单击该按钮可以将照片添加到他们的个人资料中,这张照片也会添加到 ViewPager 中,我将其用作幻灯片来显示图像。离开此活动后,图像也会上传到我的在线数据库。感谢您的帮助。
    猜你喜欢
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多