Service Intent must be explicit

作者: 爱吃馒头的二饼 | 来源:发表于2018-05-21 17:12 被阅读11次

    我们在隐式开启一个服务的时候,可能会遇到这个错误

    IllegalArgumentException: Service Intent must be explicit
    

    我在使用AIDL时,开启服务就报了如上错误。

    原因

    • Android 5.0,service必须采用显示方式启动,如下是相关源码:
    ContextImpl.java 部分源码(Android N)

    解决方法

    从源码上看,我们有两种解决上述问题的办法:

    • 第一种:用显式意图替换隐式意图
    Intent mIntent = new Intent();
    mIntent.setAction("XXX.XXX.XXX");
    Intent intent = new Intent(getExplicitIntent(mContext,mIntent));
    context.startService(intent );
    
    • 第二种:设置packageName
    Intent mIntent = new Intent();
    mIntent.setAction("XXX.XXX.XXX");
    mIntent.setPackage("XXX.XXX.XXX");//Service所在应用的包名
    context.startService(mIntent);
    

    举例

    报错的写法:

            Intent intent = new Intent("com.hansion.aidls.HaHaService");
            bindService(intent,mConnection,Context.BIND_AUTO_CREATE);
    

    使用第二种方法解决的例子:

            Intent intent = new Intent();
            intent.setAction("com.hansion.aidls.HaHaService");
            intent.setPackage("com.hansion.aidls");
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    

    相关文章

      网友评论

        本文标题:Service Intent must be explicit

        本文链接:https://www.haomeiwen.com/subject/txhqjftx.html