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

来源:互联网 发布:淘宝网找胶片老相机 编辑:程序博客网 时间:2024/06/05 01:10

报错原因:

(摘自:http://blog.csdn.net/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 meintent.setPackage("com.a.b");

或者更优雅地链式调用:

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





0 0