【问题标题】:How to recycle a bitmap in a AsyncTask? Android如何在 AsyncTask 中回收位图?安卓
【发布时间】:2013-06-16 12:07:34
【问题描述】:

我正在编写一个小型 android 应用程序,它使用 asyncTask 来显示来自 Web 服务的图像。代码有效,但我注意到我应该回收这个位图。

我的问题是,有没有办法在我用完后回收这个位图?

我尝试了使用 onStop() 的解决方案,但位图没有被回收或图像根本不会显示。

这是我的 OnCreate

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Other unrelated things
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        imageUrl = bundle.getString("imageUrl");
        displayImage();
    }

这是我的异步任务

private void displayImage() {
        new AsyncTask<String, Void, Bitmap>() {
            protected Bitmap doInBackground(String... params) {
                try {
                    return loadBitmap(params[0]);
                } catch (Exception e) {
                    Logger.e(TAG, getString(R.string.error_loading_image_bitmap));
                    return null;
                }
            }

            protected Bitmap loadBitmap(String urlSpec) throws IOException {
                InputStream is = new URL(urlSpec).openStream();
                try {
                    return BitmapFactory.decodeStream(is);
                } finally {
                    is.close();
                } 
            }

            protected void onPostExecute(Bitmap bitmap) {
                if (bitmap != null) {
                    ImageView invoiceItemImageView = (ImageView) findViewById(R.id.some_id_here);
                    invoiceItemImageView.setImageBitmap(bitmap);

                }

            }

        }.execute(imageUrl);

    }

【问题讨论】:

    标签: android bitmap android-asynctask recycle


    【解决方案1】:

    覆盖方法View.onDetachedFromWindow() 并在那里回收你的Bitmap

    【讨论】:

      猜你喜欢
      • 2016-02-25
      • 2023-02-03
      • 1970-01-01
      • 2023-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      相关资源
      最近更新 更多