资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Android应用中出现ServiceIntentmustbeexplicit报错如何解决

Android 应用中出现Service Intent must be explicit报错如何解决?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

成都网络公司-成都网站建设公司创新互联建站十年经验成就非凡,专业从事成都网站建设、成都做网站,成都网页设计,成都网页制作,软文营销1元广告等。十年来已成功提供全面的成都网站建设方案,打造行业特色的成都网站建设案例,建站热线:13518219792,我们期待您的来电!

Android 出现的警告(Service Intent must be explicit)解决办法详解

有些时候我们使用Service的时需要采用隐私启动的方式,但是Android 5.0一出来后,其中有个特性就是Service Intent  must be explitict,也就是说从Lollipop开始,service服务必须采用显示方式启动。

而android源码是这样写的

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);

2、将隐式启动转换为显示启动:

public static Intent getExplicitIntent(Context context, Intent implicitIntent) {
  // Retrieve all services that can match the given intent
  PackageManager pm = context.getPackageManager();
  List 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 应用中出现Service Intent must be explicit报错如何解决问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


文章名称:Android应用中出现ServiceIntentmustbeexplicit报错如何解决
标题路径:http://cdkjz.cn/article/pgjsdi.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220