我們?cè)陔[式開啟一個(gè)服務(wù)的時(shí)候,可能會(huì)遇到這個(gè)錯(cuò)誤
IllegalArgumentException: Service Intent must be explicit
我在使用AIDL時(shí)宜狐,開啟服務(wù)就報(bào)了如上錯(cuò)誤肛搬。
原因
- Android 5.0,service必須采用顯示方式啟動(dòng),如下是相關(guā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);
舉例
報(bào)錯(cuò)的寫法:
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);