Android 出现的警告(Service Intent must be explicit)解决办法详解
程序员文章站
2022-10-24 17:10:32
android 出现的警告(service intent must be explicit)解决办法详解
有些时候我们使用service的时需要采用隐私启动的方式,但是a...
android 出现的警告(service intent must be explicit)解决办法详解
有些时候我们使用service的时需要采用隐私启动的方式,但是android 5.0一出来后,其中有个特性就是service intent must be explitict,也就是说从lollipop开始,service服务必须采用显示方式启动。
而android源码是这样写的(源码位置:sdk/sources/android-21/android/app/contextimpl.java):
private void validateserviceintent(intent service) { if (service.getcomponent() == null && service.getpackage() == null) { if (getapplicationinfo().targetsdkversion >= build.version_codes.lollipop) { illegalargumentexception ex = new illegalargumentexception( "service intent must be explicit: " + service); throw ex; } else { log.w(tag, "implicit intents with startservice are not safe: " + service + " " + debug.getcallers(2, 3)); } } }
既然,源码里是这样写的,那么这里有两种解决方法:
1、设置action和packagename:
参考代码如下:
intent mintent = new intent(); mintent.setaction("xxx.xxx.xxx");//你定义的service的action mintent.setpackage(getpackagename());//这里你需要设置你应用的包名 context.startservice(mintent);
此方式是google官方推荐使用的解决方法。
在此附上地址供大家参考:http://developer.android.com/goo ... tml#billing-service,有兴趣的可以去看看。
2、将隐式启动转换为显示启动:--参考地址:http://*.com/a/26318757/1446466
public static intent getexplicitintent(context context, intent implicitintent) { // retrieve all services that can match the given intent packagemanager pm = context.getpackagemanager(); list<resolveinfo> resolveinfo = pm.queryintentservices(implicitintent, 0); // make sure only one match was found if (resolveinfo == null || resolveinfo.size() != 1) { return null; } // get component info and create componentname resolveinfo serviceinfo = resolveinfo.get(0); string packagename = serviceinfo.serviceinfo.packagename; string classname = serviceinfo.serviceinfo.name; componentname component = new componentname(packagename, classname); // create a new intent. use the old one for extras and such reuse intent explicitintent = new intent(implicitintent); // set the component to be explicit explicitintent.setcomponent(component); return explicitintent; }
调用方式如下:
intent mintent = new intent(); mintent.setaction("xxx.xxx.xxx"); intent eintent = new intent(getexplicitintent(mcontext,mintent)); context.startservice(eintent);
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
下一篇: Android实现价格走势自定义曲线图