2013-03-02 142 views
0

我正在开发需要运行前台服务的服务,用户可以通过活动将其切换/关闭。所以基本上,活动可能会被杀死,但只要服务不被用户阻止,服务就是安全的。切换服务活动

但是,我遇到了这个麻烦:如何关闭服务,如果它是?这意味着,如果我的活动被杀死,然后重新启动,所以我没有提到启动的服务意向调用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; 
    } 
} 

请告诉我如何正确地停止服务。谢谢。 P:我知道一个招数使serviceIntentstatic,但我不觉得安全。如果没有其他方法,那么我会使用它。

回答

1

只需在活动的onCreate中初始化您的serviceIntent即可启动您的服务,杀死您的活动,重新打开它并使用相同的serviceIntent停止服务。

+0

非常好:)非常感谢。 – 2013-03-02 10:43:14