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