错误:java.lang.IllegalArgumentException: Service not registered

问题

在做Service的绑定和解绑小项目测试的时候,绑定成功,解绑也成功,但是如果解除绑定后再点击给解除绑定的指令(项目中就是点击按钮解除绑定),会报这个错误:

AndroidRuntime(7090): java.lang.IllegalArgumentException: Service not registered: 
com.m1910.servicetest.MainActivity$1@41ddfcc0

错误提示Service没有注册,事实上我在Manifest.xml中已经注册过这个Service了。

修改前代码:

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.start_service:
            Intent startIntent = new Intent(this, MyService.class);
            startService(startIntent);// 启动服务
            break;
        case R.id.stop_service:
            Intent stopIntent = new Intent(this, MyService.class);
            stopService(stopIntent);// 停止服务
            break;
        case R.id.bind_service:
            Intent bindIntent = new Intent(this, MyService.class);
                        // 绑定服务
            bindService(bindIntent, connection, BIND_AUTO_CREATE);
            break;
        case R.id.unbind_service:
            unbindService(connection);// 解绑服务   
            break;
        default:
            break;
        }
    }

原因

查询官方文档中关于unbindService()这个方法的介绍:

public abstract void unbindService (ServiceConnection conn)

Added in API level 1
Disconnect from an application service. You will no longer receive calls as the service is restarted, and the service is now allowed to stop at any time.

Parameters
conn    The connection interface previously supplied to bindService(). This parameter must not be null.

最后一句看到这个传入的conn参数不能为null,也就是必须有绑定存在,才能解绑,小项目中绑定成功后第一次点击解绑不会报错,解绑后这个参数就是null了,再次点击解绑就会报错,那么我们为解绑加一个判断就可以了。

修改后代码如下:

private boolean isBound = false;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.start_service:
            Intent startIntent = new Intent(this, MyService.class);
            startService(startIntent);// 启动服务
            break;
        case R.id.stop_service:
            Intent stopIntent = new Intent(this, MyService.class);
            stopService(stopIntent);// 停止服务
            break;
        case R.id.bind_service:
            Intent bindIntent = new Intent(this, MyService.class);
                        // 绑定服务
            isBound = bindService(bindIntent, connection, BIND_AUTO_CREATE);
            break;
        case R.id.unbind_service:
            if (isBound) {
                unbindService(connection);// 解绑服务
                isBound = false;
            }
            break;
        default:
            break;
        }
    }

网上也有人用getApplicationContext().unbindService(mConnection);这样来做,什么意思我也不太懂,不过最终效果一样也是要加一个是否为空的判断。

错误:java.lang.IllegalArgumentException: Service not registered

原文链接:https://beltxman.com/1299.html,若无特殊说明本站内容为 行星带 原创,未经同意禁止转载。

错误:java.lang.IllegalArgumentException: Service not registered”上有 17 条评论;

评论已关闭。

Scroll to top