Caused by: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.aid

解决Service Intent must be explicit 崩溃问题

Caused by: java.lang.IllegalArgumentException:
Service Intent must be explicit: Intent { act=com.aidl.server.myserver }



今天在写一个app间通信的功能时,出现了些小问题,客户端通过aidl绑定服务端的服务,结果在client端应用启动时出现了崩溃,最初代码是这样写的:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    Intent intent = new Intent("com.aidl.server.myserver");
    bindService(intent, conn, Context.BIND_AUTO_CREATE);
}



错误log如下:

Service Intent must be explicit: Intent { act=com.aidl.server.myserver }



跟了一下源码,发现在ContextImpl中有如下的判断:

@Override
public boolean bindService(Intent service, ServiceConnection conn,
            int flags) {
    warnIfCallingFromSystemProcess();
    return bindServiceCommon(service, conn, flags, mMainThread.getHandler(),
            Process.myUserHandle());
}
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, Handler
            handler, UserHandle user) {
    ...
    validateServiceIntent(service);
    ...
}

private void validateServiceIntent(Intent service) {
    if (service.getComponent() == null && service.getPackage() == null) {
        if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
            IllegalArgumentException ex = new IllegalArgumentException(
                        "Service Intent must be explicit: " + service);
            throw ex;
        } else {
            Log.w(TAG, "Implicit intents with startService are not safe: " + service
                    + " " + Debug.getCallers(2, 3));
        }
    }
}



由此可见,在Android5.0中增加了对intent的判断,因为intent是通过设置action得到的,因此没有Component对象的实例,也没有包名,故而报错。原因找到,增加了一个设置包名的步骤,而且需要是App的包名,而不是Service类所在包的包名,即可顺利解决,代码如下:

I

        Intent intent = new Intent("com.aidl.server.myserver");
        intent.setPackage("com.aidl.server.myserver");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);


 

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值