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

拥有回忆 提交于 2019-12-03 21:06:31

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

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.

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;
    }

}

 }

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.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...

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...

For the callback there is a good example here.

First of all, onPostExecute executes 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:

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();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!