1

我正在退出選項在我的偏好活動。在該選項中,我想解除並停止服務。但我的應用程序已關閉,但服務不會停止。我從另一項活動開始並約束服務。在偏好活動中,我沒有開始或有約束力。停止和取消綁定服務來自不同的活動在android

這裏是我的偏好活動代碼:

Preference exit = findPreference("Exit"); 
     exit.setOnPreferenceClickListener(new OnPreferenceClickListener() { 

      public boolean onPreferenceClick(Preference preference) { 
       // TODO Auto-generated method stub 
       new AlertDialog.Builder(SettingsActivity.this) 
       .setTitle("Exit :") 
       .setMessage("Are You Sure??") 
       .setNegativeButton("No", null) 
       .setPositiveButton("Yes", 
         new Dialog.OnClickListener() { 
          public void onClick(DialogInterface dialog, int which) { 

           stopService(new Intent(getApplicationContext(), MyService.class));        
           Intent intent = new Intent(Intent.ACTION_MAIN); 
           intent.addCategory(Intent.CATEGORY_HOME); 
           intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
           startActivity(intent); 
          } 
         }) 
       .show(); 
       return true; 
      } 
     }); 

但爲MyService不會停止。我如何阻止我的服務? pleaze幫助我..

編輯:

遇到錯誤,我已經改變

01-24 10:20:30.699: E/AndroidRuntime(18503): FATAL EXCEPTION: main 
01-24 10:20:30.699: E/AndroidRuntime(18503): java.lang.IllegalArgumentException: Service not registered: [email protected] 
01-24 10:20:30.699: E/AndroidRuntime(18503): at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:891) 
01-24 10:20:30.699: E/AndroidRuntime(18503): at android.app.ContextImpl.unbindService(ContextImpl.java:901) 
01-24 10:20:30.699: E/AndroidRuntime(18503): at android.content.ContextWrapper.unbindService(ContextWrapper.java:352) 

代碼:

getApplicationContext().stopService(new Intent(SettingsActivity.this, MyService.class));     getApplicationContext().unbindService(serviceConnection); 

回答

5

通常服務被停止在或您最後onDestroy活動。

我在項目中的一個使用此代碼:

@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    getApplicationContext().unbindService(service); 
} 

此代碼退出在退出我的應用我的服務。

+0

我的Ondestroy()方法沒有被調用..你寫什麼來退出應用程序? – zanky

+0

沒什麼特別的,它是一項活動的正常活動週期。 Android需要一段時間才能殺死一個後臺應用程序。如果你處理旋轉事件,你也可以使用onPause。 – rekire

+0

請參閱[活動生命週期](http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle)。 – rekire