我有一个绑定在onPause()
中的服务,如果应用程序是由用户后台或关闭的,则我的应用程序会将MediaPlayer
之类的数据传递给该服务。但是说用户关闭应用程序而不是后台应用程序。我仍然希望将数据传递给服务,但是如果在绑定服务之前调用onDestory()
会怎样。这有可能吗?我应该添加一个计时器来对boundness
个服务进行采样,然后再允许应用关闭,并给采样算法超时吗?我希望能够在应用被终止之前将数据传递给服务。
修改
这就是我最终要做的。我想我会测试一下。
@Override
protected void onPause() {
super.onPause();
// Create bound service with notification when app is backgrounded or killed
// and pass media player to bound service so user can control media player
// from notification.
bindMediaPlayerService();
// It might be possible that if the user closes the app that the service will not be bound
// before onDestroy() is called. After onPause() is called, the app should no longer be
// visible, so it should be okay to add a waiter here in the form of a sampler which
// samples the boundedness of the service for N seconds before timing out.
sampleBoundednessOfServiceUntilTimeOut(5);
}
private void sampleBoundednessOfServiceUntilTimeOut(int timeOutSec)
{
Log.d(TAG,"sampleBoundednessOfServiceUntilTimeOut() timeOutSec="+timeOutSec);
long startSec = System.currentTimeMillis();
while(true)
{
if(mBound)
{
Log.d(TAG,"service bound in time, no time out required");
break;
}
long endSec = System.currentTimeMillis();
if(endSec - startSec > timeOutSec)
{
Log.d(TAG,"service did not bind in time, timing out");
break;
}
}
}