我正在我的应用程序中创建一项服务来下载图像,我不清楚如何将结果(位图)从服务发送到主要 Activity 。我可以这样做吗?或者在服务中只能将下载的图像保存在某处并仅发送无用的消息?
最佳答案
尝试从 Activity 绑定(bind)到服务,然后将 Activity 的实例传递给服务。在这种情况下,您可以将位图从服务传递到 Activity 。但是,您需要非常小心,不要引入内存泄漏
类似这样的事情:
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);
}
}
您的服务方:
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();
}
}
}
关于java - 如何将位图从服务发送到 java、android 中的主程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25461862/