android - 停止并取消绑定(bind) Android 中不同 Activity 的服务

标签 android android-activity android-service android-preferences

我在我的偏好 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 的onPauseonDestroy中停止。

我在我的一个项目中使用此代码:

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

此代码在退出我的应用程序时退出我的服务。

关于android - 停止并取消绑定(bind) Android 中不同 Activity 的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14479727/

相关文章:

java - 删除多行Edittext android中的下一行可见性

android - type_linear_acceleration 的权限

Android内存泄漏,没有静态变量

android - Firebase 测试实验室覆盖,Orchestrator 权限被拒绝

java - Android:闲置 X 分钟后重新打开应用程序?

android - 在同一屏幕上显示多个 Activity

android - 如果 Android 需要更多内存,它会决定放弃什么?

android - 当 Activity 在前台时接收明确的 Intent

java - 服务如何无限期运行并允许在android中绑定(bind)?

java - 无法从 Android 读取 SQLite 表