Android(安卓)5.0之后禁止用隐式Intent启动Service
16lz
2021-01-26
如果用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)); } } }
因此在做开发时一定要注意版本兼容,做好适配和测试。
更多相关文章
- [Android6.0]App中调用init.rc中的服务,从而运行shell脚本
- android studio 真机调试连接时候好好的,运行安装就掉线 Session
- android studio关于 Gradle sync failed: Connection timed out:
- 【android】数据库升级完整解决方案
- Android(安卓)转场动画使用,所遇到的坑
- Android(安卓)5.0的调度作业JobScheduler
- Android系统工具之自动化测试(2)
- Unable to resolve target 'android-XX'问题
- Android闹钟及相关组件