解决Android5.0及以上启动Service时,java.lang.IllegalArgumentException: Service Intent must be explicit

文章详细介绍了在Android5.0及以上版本中,Service服务必须采用显示方式启动的原因,并提供了通过设置包名来解决该问题的方法。解决方案包括直接设置包名或使用链式调用方式实现。

报错原因:

(摘自:http://blog.youkuaiyun.com/vrix/article/details/45289207)

有些时候我们使用Service的时需要采用隐私启动的方式,但是Android 5.0一出来后,其中有个特性就是Service Intent  must be explitict,也就是说从Lollipop开始,service服务必须采用显示方式启动。
而android源码是这样写的(源码位置:sdk/sources/android-21/android/app/ContextImpl.java):

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));
            }
        }
    }


解决方案:

(From:http://stackoverflow.com/questions/24480069/google-in-app-billing-illegalargumentexception-service-intent-must-be-explicit/26318757#26318757)

Intent intent = new Intent("com.a.b.cservice");
// This is the key line that fixed everything for me
intent.setPackage("com.a.b");

或者更优雅地链式调用:

Intent intent = new Intent("com.a.b.cservice").setPackage("com.a.b");





评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值