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
- Android 5.0之后禁止用隐式Intent启动Service
- Android 5.0之后使用隐式Intent方式启动Service
- Android 5.0 禁止使用隐式Intent来启动Service.异常:service intent must be explicit
- Android 5.0之后隐式声明Intent 启动Service引发的问题
- Android 5.0之后隐式声明Intent 启动Service引发的问题
- Android 5.0之后隐式声明Intent 启动Service引发的问题
- Android 5.0之后隐式声明Intent 启动Service引发的问题
- Android 5.0之后隐式声明Intent 启动Service引发的问题
- Android 5.0之后隐式声明Intent 启动Service引发的问题
- Android 5.0之后隐式声明Intent 启动Service引发的问题
- Android 5.0之后隐式声明Intent 启动Service引发的问题
- android5.0之后不允许使用隐式Intent启动Service
- Android 5.0之后启动Service 服务的方式
- 解决Android 5.0版本之后出现的异常:Service Intent must be explicit
- Android使用Intent启动Service的Intent必须是显式的
- Android 5.0 不再允许使用隐式Intent来启动Service
- AIDL通信 android 在5.0以使用隐式Intent方式来启动Service的问题
- Android 5.0 Service Intent must be explicit
- bsearch代码实现
- Pytho django与数据库的交互
- 控制Elasticsearch分片和副本的分配
- mysql 5.0存储过程学习总结
- jersey+maven构建restful服务--入门篇
- Android 5.0之后禁止用隐式Intent启动Service
- STL学习-map
- HTML 事件属性
- 回顾些简单却曾经挡着我的point
- 第7周项目4-队列数组
- kxmovie 的使用 步骤
- 第八周项目1-建立顺序串的算法库
- Python mysql中文乱码问题
- javascript 取整,取余数