我在我的偏好 Activity 中提供退出选项。在该选项中我想解除绑定(bind)并停止服务。但是我的应用程序关闭了,但服务没有停止。我正在从另一个 Activity 启动并绑定(bind)服务。在偏好 Activity 中,我没有开始或绑定(bind)。
这是我的偏好 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;
}
});
但是我的服务并没有停止。我如何停止我的服务?请帮助我..
编辑:
出现错误
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: com.androidhive.musicplayer.SettingsActivity$1@405c7af8
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);
最佳答案
通常,服务会在您的最后 Activity 的onPause
或onDestroy
中停止。
我在我的一个项目中使用此代码:
@Override
protected void onDestroy() {
super.onDestroy();
getApplicationContext().unbindService(service);
}
此代码在退出我的应用程序时退出我的服务。
关于android - 停止并取消绑定(bind) Android 中不同 Activity 的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14479727/