启动 Service 出现 Service Intent must be explicit 三种解决方法

来源:互联网 发布:java字符串前后去空格 编辑:程序博客网 时间:2024/06/07 08:56

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

private void validateServiceIntent(Intent service) {
  1.         if (service.getComponent() == null && service.getPackage() == null) {
  2.             if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
  3.                 IllegalArgumentException ex = new IllegalArgumentException(
  4.                         "Service Intent must be explicit: " + service);
  5.                 throw ex;
  6.             } else {
  7.                 Log.w(TAG, "Implicit intents with startService are not safe: " + service
  8.                         + " " + Debug.getCallers(2, 3));
  9.             }
  10.         }
  11.     }
1、设置Action和packageName:

参考代码如下:
  1. Intent mIntent = new Intent();
  2. mIntent.setAction("XXX.XXX.XXX");//你定义的service的action
  3. mIntent.setPackage(getPackageName());//这里你需要设置你应用的包名
  4. context.startService(mIntent);

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

参考代码如下:

  1. Intent mIntent = new Intent();
  2. mIntent.setAction("XXX.XXX.XXX");
  3. Intent eintent = new Intent(getExplicitIntent(mContext,mIntent));
  4. context.startService(eintent);

3、根据源码:getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP,可将build.gradle文件里的targetSdkVersion版本改低点<21即可


阅读全文
0 0
原创粉丝点击