I'm making a service in my application to download images, that's unclear for me how can i send result (bitmap) from service to a main activity. Can I do that? Or in service there is only a possibitlity to save downloaded image somewhere and send only useless messages?
2 Answers
Try binding from the activity to the service and then pass the instance of the activity to the service. In this case you can pass bitmap from a service to the activity. However, you need to be real careful not introduce memory leaks
Something like this:
class TestActivity extends Activity {
private BitmapService mBitmapService;
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName,
IBinder iBinder) {
BitmapService.BitmapServiceBinder mBinder = (BitmapService.BitmapServiceBinder) iBinder;
mBitmapService = mBinder.getBitmapService();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bindService(new Intent(this, XMLDownloaderService.class), mServiceConnection, BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(this.mServiceConnection);
}
}
Your Service Side:
public class BitmapService extends BitmapService {
public class BitmapServiceBinder extends Binder {
public BitmapService getBitmapService() {
return BitmapService.this;
}
}
public BitmapService() {
super("BitmapService");
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
if (mBinder == null) {
mBinder = new BitmapServiceBinder();
}
}
}

- 1,882
- 2
- 16
- 17
Bitmap
implements Parcelable
, so you could always pass it in the intent:
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);
and retrieve it on the other end:
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
If the bitmap exists as a file or a resource, its is always better to pass the URI or ResourceID of the bitmap and not the bitmap itself. Passing the entire bitmap requires a lot of memory. Passing the URL requires very little memory and allows each activity to load and scale the bitmap as they need it.
Answer pullout from: How can I pass a Bitmap object from one activity to another