Java 如何从 Android 应用程序中的异步任务返回位图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23960025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:25:47  来源:igfitidea点击:

How to return a Bitmap from an Async Task in Android app

javaandroidbitmapandroid-asynctaskimageview

提问by user1282637

Ok, so this code is right off the Android Developer site which sets an ImageViewto a Bitmap:

好的,所以这段代码就在 Android 开发者网站上,它将 an 设置ImageView为 a Bitmap

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private int data = 0;

public BitmapWorkerTask(ImageView imageView) {
    // Use a WeakReference to ensure the ImageView can be garbage collected
    imageViewReference = new WeakReference<ImageView>(imageView);
}

// Decode image in background.
@Override
protected Bitmap doInBackground(Integer... params) {
    data = params[0];
    return decodeSampledBitmapFromResource(getResources(), data, 100, 100));
}

// Once complete, see if ImageView is still around and set bitmap.
@Override
protected void onPostExecute(Bitmap bitmap) {
    if (imageViewReference != null && bitmap != null) {
        final ImageView imageView = imageViewReference.get();
        if (imageView != null) {
            imageView.setImageBitmap(bitmap);
        }
    }
}
}

And basically, what I want to do is instead of doing

基本上,我想做的是而不是做

imageView.setImageBitmap(bitmap);I want to return that Bitmapso I can then use it in my Main UI. Is there any way of going about doing this? Sorry about my lack of knowledge on AsyncTask, I just started learning it recently. Thank you!

imageView.setImageBitmap(bitmap);我想返回它,Bitmap以便我可以在我的主 UI 中使用它。有没有办法做到这一点?很抱歉我缺乏关于 的知识AsyncTask,我最近才开始学习。谢谢!

采纳答案by umerk44

Actually there is no need to return bitmap and than use it in main Ui Thread. You can do this on PostExecute becuase postExecute runs in UI Thread. Your question?? Yes you can return bitmap from AsynTask you can do something like this

实际上不需要返回位图,而是在主 Ui 线程中使用它。您可以在 PostExecute 上执行此操作,因为 postExecute 在 UI 线程中运行。你的问题??是的,您可以从 AsynTask 返回位图,您可以执行以下操作

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


      protected Bitmap doInBackground(Void... params) {

            //do stuff
             return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            //do stuff

            }
        }

Now you can get bitmap by calling

现在您可以通过调用获取位图

 Bitmap returned_bitmap = new myTask().execute().get()

Again this is not good this will hang your UI. But you can get value from Aysnc like this.

同样,这不好,这会挂起您的用户界面。但是你可以像这样从 Aysnc 获得价值。

Another method you can do is by implementing callback using interface

您可以做的另一种方法是使用接口实现回调

public interface MyInterface 
{
   public void onPostExecute();
}

Activity class

活动课

 public class MyActivity extends Activity implements MyInterface{

private Bitmap Image;

public void onCreate(Bundle b)
{
    super.onCreate(b);

    new MyTask(this).execute();
}

@Override
public void onPostExecute() {
        //Now you have your bitmap update by do in background 
    //do stuff here 
}


private class MyTask extends AsyncTask<Void, Void, Void>
{
    MyInterface myinterface;

    MyTask(MyInterface mi)
    {
        myinterface = mi;
    }

    @Override
    protected Void doInBackground(Void... params) {
        //firt declare bitmap as class member of MyActivity 
        //update bitmap here and then call

        myinterface.onPostExecute();

        return null;
    }

}

 }

回答by Rod_Algonquin

You could either use a callback method through interface or put the asynctask as a inner class and just call the some method for setting the imageView...

您可以通过接口使用回调方法,也可以将 asynctask 作为内部类,然后调用 some 方法来设置 imageView ...

For the callback there is a good example here.

回调有一个很好的例子在这里

回答by Mika

You should save yourself a lot of time and use Picasso. This will save you all of this code and it works with bitmaps. Basically you will write something like this:

您应该节省大量时间并使用Picasso。这将为您节省所有这些代码,并且它适用于位图。基本上你会写这样的东西:

Picasso.with(context).load("www.somthing.com/api/blah").placeholder(R.drawable.default_picture).into(imageView);

It's one line of code and you got Async and caching for free...

这是一行代码,您可以免费获得异步和缓存...

回答by ashishduh

First of all, onPostExecuteexecutes on your UI thread, so you don't need to do anything differently from the example. But you can always use anonymous classes if you want:

首先,onPostExecute在您的 UI 线程上执行,因此您无需执行与示例不同的任何操作。但是,如果您愿意,您始终可以使用匿名类:

public class MyActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        AsyncTask task = new BitmapWorkerTask() {
            @Override
            public void onPostExecute(Bitmap bitmap) {
                // Do whatever
            }
        };

        task.execute();
    }
}