我在 preference activity 中添加了 exit 选项,在这个选项中我想停止和取消服务。但是程序关了,服务器没有停止。我从另一个 activity 中开启和绑定服务。在 preference activity 中我没有开启也没绑定。
preference activity 代码:
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 不能停止。如何停止服务器?
获得的错误:
08-28 10:20:30.699: E/AndroidRuntime(18503): FATAL EXCEPTION: main
08-28 10:20:30.699: E/AndroidRuntime(18503): java.lang.IllegalArgumentException: Service not registered: com.androidhive.musicplayer.SettingsActivity$1@405c7af8
08-28 10:20:30.699: E/AndroidRuntime(18503): at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:891)
08-28 10:20:30.699: E/AndroidRuntime(18503): at android.app.ContextImpl.unbindService(ContextImpl.java:901)
08-28 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);