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

如果用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));  
            }  
        }  
    }  

因此在做开发时一定要注意版本兼容,做好适配和测试。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值