Android 切换服务活动
我正在开发一个需要运行前台的服务,用户可以通过活动打开/关闭它。因此,基本上,活动可能会被终止,但只要用户不停止服务,服务是安全的 然而,我遇到了一个问题:如果服务打开,如何关闭它?这意味着,如果我的活动被终止,然后重新启动,那么我就不会得到已启动服务的引用,也不会调用Android 切换服务活动,android,service,Android,Service,我正在开发一个需要运行前台的服务,用户可以通过活动打开/关闭它。因此,基本上,活动可能会被终止,但只要用户不停止服务,服务是安全的 然而,我遇到了一个问题:如果服务打开,如何关闭它?这意味着,如果我的活动被终止,然后重新启动,那么我就不会得到已启动服务的引用,也不会调用stopService 下面是我当前的代码。如果用户呼叫在同一活动启动服务后停用,则可以正常工作。按钮状态始终正确,但当操作系统重新启动“我的活动”时,this.serviceIntent为空 protected boolean
stopService
下面是我当前的代码。如果用户呼叫在同一活动启动服务后停用,则可以正常工作。按钮状态始终正确,但当操作系统重新启动“我的活动”时,this.serviceIntent
为空
protected boolean isServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (SynchronizationService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
@Override
protected void onResume() {
super.onResume();
this.togglingByCode = true;
this.butActivate.setChecked(this.isServiceRunning());
this.togglingByCode = false;
}
public void onActivateButtonClick(final boolean pIsChecked) {
if (this.togglingByCode) { return; }
if (pIsChecked) {
this.saveSettings();
this.serviceIntent = new Intent(this, SynchronizationService.class);
this.serviceIntent.putExtra(KEY_WEBSERVICE, this.txtWebService.getText().toString());
this.serviceIntent.putExtra(KEY_PASSWORD, this.txtPassword.getText().toString());
this.serviceIntent.putExtra(KEY_INTERVAL, Integer.parseInt(this.txtRefreshInterval.getText().toString()));
this.serviceIntent.putExtra(KEY_TIMEOUT, this.preferences.getInt(KEY_TIMEOUT, DEFAULT_TIMEOUT));
this.serviceIntent.putExtra(KEY_RETRY, this.preferences.getInt(KEY_RETRY, DEFAULT_RETRY));
this.startService(this.serviceIntent);
} else {
this.stopService(this.serviceIntent);
this.serviceIntent = null;
}
}
请告诉我如何正确停止服务。多谢各位
附言:我知道一个让
serviceIntent
静态的技巧,但我觉得不安全。如果没有其他方法,那么我将使用它。只需在活动的onCreate中初始化serviceIntent。。。您可以使用相同的serviceIntent启动服务、终止活动、重新打开并停止服务 非常好:)非常感谢。