Joh*_*lin 5 android callback android-service
再一个关于LocalServices的问题.在onDestroy()之后,如何(重新)绑定到现有服务?
问题:
我绑定了一个服务并从一个Activity启动服务.我将可运行的对象发布到Binder,用于在UI上进行回调(更新进度条).当我关闭这个Activity时,OS可以结束生命周期并销毁Activity,调用onDestroy(),对吗?我模拟了这个,在onPause()方法中调用finish().所以一旦我重新启动Activity,如何再次绑定到SAME服务?我认为服务是Singelton,但是当我试图重新绑定时,我得到另一个绑定器参考.所以binder.callbackHandler.post(binder.progressHandler);仍然引用旧的binder/callback/progressHandler,而不是我的新引用.甚至再次调用服务的构造函数!
是否有任何解决方案可以使用进度条,通过服务中的回调对象进行更新(正常工作).Closing/onDestroy()活动.回来,继续进度吧?
我的代码非常大,但重新创建了Szenario:
public class MyService extends Service {
private final LocalBinder binder = new LocalBinder();
public class LocalBinder extends Binder implements TestRunServiceBinder {
private Handler callbackHandler;
private ServiceStartActivity.RunOnServiceProgress onProgress;
@Override
public void setActivityCallbackHandler(Handler messageHandler) {
callbackHandler = messageHandler;
}
@Override
public void setServiceProgressHandler(RunOnServiceProgress runnable) {
onProgress = runnable;
}
public void doSomething(){
_doSomething();
};
private void _doSomething(){
while(...){
//do this a couple of times (could take up to 10min)
binder.callbackHandler.post(binder.progressHandler);
wait()
}
}
}
Run Code Online (Sandbox Code Playgroud)
_
public class ServiceStartActivity{
private final Handler messageHandler = new Handler();
private ServiceConnection mTestServiceConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
testRunBinder = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
testRunBinder = (TestRunServiceBinder) service;
testRunBinder.setActivityCallbackHandler(messageHandler);
testRunBinder.setServiceProgressHandler(new RunOnServiceProgress());
}
};
@Override
protected void onStart() {
super.onStart();
// bind to the Service
final Intent serviceIntent = new Intent(ServiceStartActivity.this,
MyService.class);
getApplicationContext().bindService(serviceIntent,
mTestServiceConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
getApplicationContext().unbindService(mTestServiceConnection);
}
public class RunOnServiceProgress implements Runnable {
@Override
public void run() {
//do something on the UI!
}
}
}
Run Code Online (Sandbox Code Playgroud)
我现在明白了.解决方案是startService(serviceIntent);在使用绑定到Service之前进行显式调用getApplicationContext().bindService(serviceIntent,mTestServiceConnection, Context.BIND_AUTO_CREATE);
原因:当您启动服务时bindService(),它将成为绑定服务
只要另一个应用程序组件绑定到它就运行.
如果你用startService()它可以启动服务
可以无限期地在后台运行,
因此,如果你在UI上有一个progessbar,并且你希望它继续更新它,你应该启动你的服务,并在onResume()/ onPause()中绑定和取消绑定它.但要carfull:既然你手动启动了服务,你也应该手动停止它.最简单的方法是stopSelf() 在服务完成它之后调用.
即使在活动被销毁之后或者在方向改变之后,这种灵魂也包括从活动到例如进度条到同一服务的适当绑定.
| 归档时间: |
|
| 查看次数: |
5513 次 |
| 最近记录: |