Service Intent must be explicit 的解决方法

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

IllegalArgumentException: Service Intent must be explicit

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

原因

  • Android 5.0,service必须采用显示方式启动,如下是相关源码:

解决方法

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

  • 第一种:用显式意图替换隐式意图
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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章