定义服务或接收器时 "android:process" 的含义

Implication of "android:process" when defining services or receivers

当在 AndroidManifest.xml

中的 servicereceiver 中定义时,我正在深入了解属性 android:process

这是引自 docs:

android:process

The name of the process where the service is to run. Normally, all components of an application run in the default process created for the application. It has the same name as the application package. The element's process attribute can set a different default for all components. But component can override the default with its own process attribute, allowing you to spread your application across multiple processes.

If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the service runs in that process. If the process name begins with a lowercase character, the service will run in a global process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage.

在遵循有关如何编写同步服务和接收器的各种示例时,这些示例通常包含具有单独 android:process 名称的清单定义。

这是一个示例,其中定义了接收器和服务(:remote:sync

<receiver android:name="myapp.backgroundAnalysis.BackgroundAlaramReceiver"
        android:process=":remote"
        >
<intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
<service
    android:name="myapp.backgroundCloudSync.SyncService"
    android:exported="false"
    android:process=":sync">
    <intent-filter>
        <action android:name="android.content.SyncAdapter"/>
    </intent-filter>
    ...
</service>

如果我从两者中省略 android:process 实际会发生什么?我知道它们在默认进程中将是 运行,其他所有进程也是 运行s(Main、Threads?等),但这会对接收器和 SyncService 的行为产生影响吗?

这会影响应用程序在 运行ning 时的行为还是接收器会干扰同步?我知道一个服务将在主线程上 运行 但当代码被安排在主线程上 运行 时,某些东西会停止或仅延迟吗?

(这个问题的背景链接到一个问题,我需要 运行 对来自各种实体(主应用程序、接收器和 SyncAdapter)的某些共享资源进行同步操作,但共享资源无法在多进程环境中工作,因此我试图了解可能的解决方法或解决方案的含义)

will this have an impact on the behaviour of the receiver and SyncService?

不直接。

Can this impact the applications' behaviour when running

对于一个进程中的所有内容,线程安全性变得更加重要。 OTOH,这比在 2 个以上的进程中协调工作要容易得多,这样一个进程就不会影响另一个进程的工作。

I am aware than a service will be run on the main thread

服务的生命周期方法(例如,onStartCommand())将在主应用程序线程上运行;您的业​​务逻辑应该 运行 在后台线程上。无论一切都在一个进程中还是在多个进程之间拆分,你都必须这样做。

will something stall or only delay when code is scheduled to run on the main thread?

如果您的服务 运行s 代码在主应用程序线程上,它将在该代码 运行s 时阻塞该线程上的所有其他内容。这就是服务总是使用后台线程的原因。

根据您同步访问共享对象的方式,后台线程上的服务代码 运行 可能会锁定对这些共享对象的访问,因此会停止尝试访问这些对象的代码 UI。这就是为什么我们尝试组织我们的代码以避免阻塞来自 UI 对此类对象的调用,例如通过使用反应选项(LiveData、RxJava 等)。