Android 出现的警告(Service Intent must be explicit)解决办法详解
Android出现的警告(ServiceIntentmustbeexplicit)解决办法详解
有些时候我们使用Service的时需要采用隐私启动的方式,但是Android5.0一出来后,其中有个特性就是ServiceIntent mustbeexplitict,也就是说从Lollipop开始,service服务必须采用显示方式启动。
而android源码是这样写的(源码位置:sdk/sources/android-21/android/app/ContextImpl.java):
privatevoidvalidateServiceIntent(Intentservice){
if(service.getComponent()==null&&service.getPackage()==null){
if(getApplicationInfo().targetSdkVersion>=Build.VERSION_CODES.LOLLIPOP){
IllegalArgumentExceptionex=newIllegalArgumentException(
"ServiceIntentmustbeexplicit:"+service);
throwex;
}else{
Log.w(TAG,"ImplicitintentswithstartServicearenotsafe:"+service
+""+Debug.getCallers(2,3));
}
}
}
既然,源码里是这样写的,那么这里有两种解决方法:
1、设置Action和packageName:
参考代码如下:
IntentmIntent=newIntent();
mIntent.setAction("XXX.XXX.XXX");//你定义的service的action
mIntent.setPackage(getPackageName());//这里你需要设置你应用的包名
context.startService(mIntent);
此方式是google官方推荐使用的解决方法。
在此附上地址供大家参考:http://developer.android.com/goo...tml#billing-service,有兴趣的可以去看看。
2、将隐式启动转换为显示启动:--参考地址:http://stackoverflow.com/a/26318757/1446466
publicstaticIntentgetExplicitIntent(Contextcontext,IntentimplicitIntent){
//Retrieveallservicesthatcanmatchthegivenintent
PackageManagerpm=context.getPackageManager();
ListresolveInfo=pm.queryIntentServices(implicitIntent,0);
//Makesureonlyonematchwasfound
if(resolveInfo==null||resolveInfo.size()!=1){
returnnull;
}
//GetcomponentinfoandcreateComponentName
ResolveInfoserviceInfo=resolveInfo.get(0);
StringpackageName=serviceInfo.serviceInfo.packageName;
StringclassName=serviceInfo.serviceInfo.name;
ComponentNamecomponent=newComponentName(packageName,className);
//Createanewintent.Usetheoldoneforextrasandsuchreuse
IntentexplicitIntent=newIntent(implicitIntent);
//Setthecomponenttobeexplicit
explicitIntent.setComponent(component);
returnexplicitIntent;
}
调用方式如下:
IntentmIntent=newIntent();
mIntent.setAction("XXX.XXX.XXX");
Intenteintent=newIntent(getExplicitIntent(mContext,mIntent));
context.startService(eintent);
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!