Android 5.0之后禁止用隐式Intent启动Service

来源:互联网 发布:时代天使java怎么样 编辑:程序博客网 时间:2024/06/03 20:18

如果用startService()传入Intent参数启动一个Service,该Intent参数可分为显式Intent和隐式Intent。

在Android 5.0之前的版本,显式Intent和隐式Intent都可以启动service:
如下面的例子,我们想在MainActivity中启动一个MyService,可以这么写:

Intent intent = new Intent(MainActivity.this, MyService.class);startService(intent);

也可以这么做:
在Manifest文件中对Myservice加上Intent-filter,

<service android:name=".MyService">
<intent-filter>
<action android:name="android.intent.action.TEST_ACTION" />
</intent-filter>
</service>

然后在MainActivity中这么写:

Intent intent = new Intent("android.intent.action.TEST_ACTION");startService(intent);

两种方式都可以启动MyService。

但是Android 5.0及以后,Service只能通过显式Intent启动了。如果上述两种代码运行在Android 5.0的手机上,第一种可以正常运行,第二种会报错停止运行:

E/AndroidRuntime: FATAL EXCEPTION: main                  Process: com.example.test, PID: 8746                  java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=android.intent.action.TEST_ACTION }                      at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1209)                      at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1238)                      at android.app.ContextImpl.startService(ContextImpl.java:1222)

查看Android源码,这里是报错的原因:

    private void validateServiceIntent(Intent service) {          if (service.getComponent() == null && service.getPackage() == null) {              //当targetSdkVersion版本大于等于LOLLIPOP就会抛出异常            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 0
原创粉丝点击