Android 跨进程启动Service无效

在一个应用中可能需要用到其他应用提供的服务,这时可以使用隐式的方式启动服务,但是对于不同的Android版本,隐式启动的方式也略有限制

介绍两种隐式启动Service的方法

方法一:

Intent intent = new Intent();
ComponentName componentName = new ComponentName("com.example", "com.example.TestService");
intent.setComponent(componentName);
startService(intent); 或 bindService(intent, connection, BIND_AUTO_CREATE)

这种方法,Android 11 也可以正常启动

方法二:

Intent callService = new Intent();
callService.setPackage("com.example.test");
callService.setAction("com.example.test.RemoteService");
bindService(callService, serviceConnection, BIND_AUTO_CREATE); 或 startService(callService);

这种方法在Android 10(包含)之前是可以正常的启动或绑定Service的,但是如果Android版本>=11的话,使用这种方式无法正确启动Service,而且没有任何报错信息!(麻了)

在Android 11及以上的版本想使用这种方式启动的话,需要在提供服务的一方的清单文件中添加:

<queries>
   <package android:name="调用服务一方的包名"></package>
</queries>

如此方法二在Android11也可以正常运行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值