从不同的 Activity 中停止和取消服务

我在 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);

您需要在开启服务时绑定服务,并在停止服务时解绑服务。在绑定服务时,您需要使用 bindService() 方法,并传递 ServiceConnection 对象。在解绑服务时,您需要使用 unbindService() 方法,并传递与绑定服务相同的 ServiceConnection 对象。


在您的代码中,您可以尝试在开启服务时绑定服务,在停止服务时解绑服务。

private ServiceConnection serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // code here
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        // code here
    }
};

// 绑定服务
bindService(new Intent(this, MyService.class), serviceConnection, Context.BIND_AUTO_CREATE);

// 解绑服务
unbindService(serviceConnection);

并在 onPreferenceClick 中 先unbind,再stop

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) {
                                getApplicationContext().unbindService(serviceConnection);
                                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;
            }