Service Intent must be explicit 的解決方法

我們在隱式開啟一個服務(wù)的時候,可能會遇到這個錯誤

IllegalArgumentException: Service Intent must be explicit

我在使用AIDL時,開啟服務(wù)就報了如上錯誤。

原因

  • Android 5.0,service必須采用顯示方式啟動,如下是相關(guān)源碼:
ContextImpl.java 部分源碼(Android N)

解決方法

從源碼上看,我們有兩種解決上述問題的辦法:

  • 第一種:用顯式意圖替換隱式意圖
Intent mIntent = new Intent();
mIntent.setAction("XXX.XXX.XXX");
Intent intent = new Intent(getExplicitIntent(mContext,mIntent));
context.startService(intent );
  • 第二種:設(shè)置packageName
Intent mIntent = new Intent();
mIntent.setAction("XXX.XXX.XXX");
mIntent.setPackage("XXX.XXX.XXX");//Service所在應(yīng)用的包名
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);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容