Android 应用中出现Service Intent must be explicit报错如何解决

发布时间:2020-12-03 15:00:22 作者:Leah
来源:亿速云 阅读:1028

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

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> 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报错如何解决问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. 如何退出整个Android 应用
  2. Android 8.0完美适配全局dialog悬浮窗弹出的案例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android must roi

上一篇:怎么在Android应用中实现一个查看内存使用情况功能

下一篇:利用EditText怎么限制输入的数字并精确到小数点后1位

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》