android-Service_Intent_must_be_explicit的解决方法

android: Service Intent must be explicit 的解决方法

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

IllegalArgumentException: Service Intent must be explicit

原因是 android 5.0 以后,Service 必须以显式方式启动:

image-20221107135511864

解决方法

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

  • 第一种:用显式意图替换隐式意图

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

参考链接
1.Service Intent must be explicit 的解决方法
2.Service Intent must be explicit的解决方案

posted @ 2022-11-07 14:01  夜行过客  阅读(352)  评论(0编辑  收藏  举报