如何在多用户 android 系统中使我的服务仅在一个实例中 运行?

How to make my service only run in one instance in multiple user android system?

我们的 android 系统支持多用户功能。我想使用命令 startService(intent) 从其他应用程序启动我的服务器,例如 app1、app2。 根据 google 在 https://source.android.com/devices/tech/admin/multiuser-apps.html 的文档。 我需要设置 android:singleUser="true" 以确保我的服务在多用户 android 系统的一个实例中仅 运行。但是当我在其他应用程序中启动服务时,出现以下异常:

Not allowed to start service Intent { act=com.xx.xxx.action.Start pkg=com.xx.xxx (has extras) } without permission not exported from uid 1000

android:exported="true" 似乎被 android:singleUser="true" 禁用了。如果我没有添加 android:singleUser="true",它工作正常,但我的服务 运行 在后台有多个实例。 我的问题是如何使用来自其他应用程序的 startService(intent) 在一个实例中仅使我的服务 运行? 我的Manifest.xml配置如下:

    <application
        android:name=".App"
        android:label="@string/app_name"
        android:directBootAware="true"
        android:multiprocess="false"
        android:persistent="true">
        <service
            android:name=".MyService"
            android:singleUser="true"
            android:exported="true"
            android:permission="com.xx.permission.xx">
            <intent-filter>
                <action android:name="com.xx.xx.action.xx" />
            </intent-filter>
        </service>
</Application>

非常感谢。

正如您链接的文档所说:"only system apps can currently use this feature"。如果您的产品可行,请将您的应用程序设为系统应用程序。

是的,需要将应用声明为系统应用。还可以将 bindServiceAsUser() 与 System UserHandler 一起使用。

  1. 使 android:exported 和 android:singleUser 为真
  2. 添加权限INTERACT_ACROSS_USERS
  3. 确保您的应用程序具有特权。所以你应该让你的应用程序系统签名

您需要 INTERACT_ACROSS_USERS_FULL 权限才能允许从非主要用户绑定到单个实例服务。这是仅签名权限,因此您的应用需要使用平台密钥进行签名。