I want to defer the reading of a bitmap to another thread. I'm mainly concerned about concurrency issues since I'm kind of green on that subject, so I would like to know if this code has any potential flaws.
public class SomeActivity extends Activity {
Bitmap threadBitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BitmapTask().execute();
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(threadBitmap != null) {
// Assume bitmap has loaded and do something with it here
}
}
});
}
public class BitmapTask extends AsyncTask<Void, Void, Bitmap> {
@Override
protected Bitmap doInBackground(Void... params) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = getAssets().open("mybitmap.png");
bitmap = BitmapFactory.decodeStream(in);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
threadBitmap = result;
}
}
}