如果用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,





然后在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. [Android6.0]App中调用init.rc中的服务,从而运行shell脚本
  2. android studio 真机调试连接时候好好的,运行安装就掉线 Session
  3. android studio关于 Gradle sync failed: Connection timed out:
  4. 【android】数据库升级完整解决方案
  5. Android(安卓)转场动画使用,所遇到的坑
  6. Android(安卓)5.0的调度作业JobScheduler
  7. Android系统工具之自动化测试(2)
  8. Unable to resolve target 'android-XX'问题
  9. Android闹钟及相关组件

随机推荐

  1. Android(安卓)壁纸设置代码 详解
  2. Android面试题整理-3
  3. android 认识
  4. Android性能调优篇之内存泄露
  5. android ---Using java surface on the n
  6. Android(安卓)Service 两种编写及应用
  7. Android实践--模拟器的加度的快感
  8. 2012年Android技术前景分析
  9. Android实训案例(五)——四大组件之一Conte
  10. Android(安卓)中 AsyncTask 的使用