Use AsyncTask to Load Bitmap Images

后端 未结 1 1174
误落风尘
误落风尘 2021-01-14 03:38

I am trying to load an image in the background as someone works through my app. The logic I wrote is this:

public class ImageLoader extends AsyncTask 

        
相关标签:
1条回答
  • 2021-01-14 04:04

    The problem is that you are trying to access and operate on UI elements from a non UI thread. If you change your AsyncTask as follows, i believe you will be ok:

    public class ImageLoader extends AsyncTask <Void, Void, Bitmap>{
    
    private String URL;
    private int type;
    private Context context;
    private InputStream in;
    
    ImageLoader(Context context, String Url, int Type)
    {
        URL = Url;
        type = Type;
        ImageLoader.this.context = context;
    }
    
    @Override
    protected void onPreExecute()
    {
       AssetManager assetMgr = context.getAssets();
    
       try {
    
           in = assetMgr.open(URL);
       } catch (IOException e) {
    
           e.printStackTrace();
       }
    
    }
    
    @Override
    protected Bitmap doInBackground(Void... arg0) {
    
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    
    @Override
    protected void onPostExecute( Bitmap result )  {
    
          if (type == 1)
              Inst1 = result;
          else if (type == 2)
              Inst2 = result;
          else if (type == 3)
              Inst3 = result;
    }
    }
    

    Also change the call of your AyncTask to something like this:

    task = new ImageLoader(gameContext, "Instructions_2.png", 3);
    task.execute();
    
    0 讨论(0)
提交回复
热议问题