安卓11以上版本远程启动服务(启动其他应用的服务)

一、前言

大家都知道,谷歌爷爷特别喜欢搞事情,越高的版本,对于开发着来说,越麻烦,以前的远程服务启动方式,从安卓11以上的版本开始就没用了。当然并不是完全没用,需要你额外去做一些事情。
首先说一下,提供服务的应用A为服务端,访问服务的应用B为客户端,我需要在客户端启动服务端的Service。修改xml时别搞混了。

二、配置

2.1 服务端应用A的androidmanifest.xml配置如下

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.servicedemo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ServiceDemo">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService"
            android:exported="true"
            android:enabled="true">
            <intent-filter>
                <!--指定服务的action-->
                <action android:name="com.example.lyyservice"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </service>
    </application>

</manifest>

2.2 客户端应用B的androidmanifest.xml文件配置如下

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.aidldemo">

    <!--这里是关键-->
    <queries>
        <package android:name="com.example.servicedemo"/>
        <intent>
            <action android:name="com.example.lyyservice" />
        </intent>
    </queries>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AIDLDemo">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

三、客户端应用B的启动逻辑代码

Intent intent = new Intent();
intent.setAction("com.example.lyyservice");//服务端的Service的action名
intent.setPackage("com.example.servicedemo");//服务端的包名
startService(intent);

四、总结

queries这个标签是写在客户端里面的,别搞混了,一开始我就是错误地把它写到服务端里了,导致启动不了。
有些人说服务端应用A还需要在系统设置里改成自启动,并且授予“后台弹出界面”的权限,才能实现远程启动,不过我在小米10上测的,并不需要这两点,大家可以试一试。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值