Android 服务 onBind 方法接收到过时的意图
Android Service onBind method receiving stale intent
我正在实例化一个服务如下:
try {
Intent intent = new Intent(this, SOMEService.class);
intent.putExtra("key", SOME UUID);
startService(intent);
bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);
} catch (Exception e) {
}
在我服务的 onBind 方法中,我检查提供的密钥是否与服务中的预期密钥匹配。
此密钥在每次交易时都会刷新。
问题是,如果我关闭应用程序并重新打开它(强制服务重新绑定),之后 onBind 方法会收到带有陈旧密钥的先前意图,而不是带有新密钥的较新意图。
知道为什么会这样吗?
当您启动服务时,它将 运行 无限期地重新启动,即使 Android 由于缺乏资源而停止它也是如此。因此,当您关闭应用程序时,服务将保持 运行ning - 您只能从它绑定。如果您希望您的服务 运行 仅在应用程序打开时运行,请在应用程序关闭时停止它,然后重新启动。
您是否尝试检查 onStartCommand 中的意图?,因为您也在启动该服务。
根据文档:
Called by the system every time a client explicitly starts the service
by calling startService(Intent)
https://developer.android.com/reference/android/app/Service.html#onStartCommand(android.content.Intent,int,int)
示例:
public void onStartCommand (Intent intent,
int flags,
int startId)
{
String key = intent.getStringExtra("key");
}
我正在实例化一个服务如下:
try {
Intent intent = new Intent(this, SOMEService.class);
intent.putExtra("key", SOME UUID);
startService(intent);
bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);
} catch (Exception e) {
}
在我服务的 onBind 方法中,我检查提供的密钥是否与服务中的预期密钥匹配。 此密钥在每次交易时都会刷新。
问题是,如果我关闭应用程序并重新打开它(强制服务重新绑定),之后 onBind 方法会收到带有陈旧密钥的先前意图,而不是带有新密钥的较新意图。
知道为什么会这样吗?
当您启动服务时,它将 运行 无限期地重新启动,即使 Android 由于缺乏资源而停止它也是如此。因此,当您关闭应用程序时,服务将保持 运行ning - 您只能从它绑定。如果您希望您的服务 运行 仅在应用程序打开时运行,请在应用程序关闭时停止它,然后重新启动。
您是否尝试检查 onStartCommand 中的意图?,因为您也在启动该服务。
根据文档:
Called by the system every time a client explicitly starts the service by calling startService(Intent) https://developer.android.com/reference/android/app/Service.html#onStartCommand(android.content.Intent,int,int)
示例:
public void onStartCommand (Intent intent,
int flags,
int startId)
{
String key = intent.getStringExtra("key");
}