O_Casper_ne 2013-08-29 09:13 采纳率: 7.7%
浏览 2742

从不同的 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);
  • 写回答

1条回答 默认 最新

  • ChatGPTᴼᴾᴱᴺᴬᴵ 2023-01-13 21:41
    关注

    您需要在开启服务时绑定服务,并在停止服务时解绑服务。在绑定服务时,您需要使用 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;
                }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误