处理已缓存和冻结的应用

使用 binder 在进程之间进行通信时,如果远程进程处于缓存或冻结状态,请特别小心。调用缓存或冻结的应用可能会导致其崩溃或不必要地消耗资源。

已缓存和已冻结的应用状态

Android 会将应用保持在不同的状态,以管理内存和 CPU 等系统资源。

缓存状态

当应用没有用户可见的组件(例如 activity 或服务)时,可以将其移至缓存状态。如需了解详情,请参阅进程和应用生命周期。缓存的应用会保留在内存中,以防用户切换回这些应用,但这些应用不应处于活跃工作状态。

从一个应用进程绑定到另一个应用进程时(例如使用 bindService),服务器进程的进程状态会提升到至少与客户端进程一样重要(除非指定了 Context#BIND_WAIVE_PRIORITY)。例如,如果客户端未处于缓存状态,则服务器也不会处于缓存状态。

相反,服务器进程的状态也不会决定其客户端的状态。因此,服务器可能具有与客户端的 binder 连接(最常见的是回调形式),并且当远程进程处于缓存状态时,服务器不会被缓存。

在设计回调源自特权进程并传递给应用的 API 时,请考虑在应用进入缓存状态时暂停分派回调,并在应用退出此状态时恢复分派。这可以防止在缓存的应用进程中执行不必要的工作。

如需跟踪应用何时进入或退出缓存状态,请使用 ActivityManager.addOnUidImportanceListener:

Java

// in ActivityManager or Context
activityManager.addOnUidImportanceListener(
    new ActivityManager.OnUidImportanceListener() { ... },
    IMPORTANCE_CACHED);

Kotlin

// in ActivityManager or Context
activityManager.addOnUidImportanceListener({ uid, importance ->
  // ...
}, IMPORTANCE_CACHED)

冻结状态

系统可以冻结缓存的应用,以节省资源。应用被冻结后,将无法获得任何 CPU 时间,也无法执行任何工作。如需了解详情,请参阅缓存的应用冻结器。

当某个进程向另一个已冻结的远程进程发送同步(非 oneway)binder 事务时,系统会终止该远程进程。这可防止调用进程中的调用线程在等待远程进程解冻时无限期挂起,否则可能会导致调用应用中出现线程饥饿或死锁。

当进程向已冻结的应用发送异步 (oneway) binder 事务(通常通过通知回调,通常是 oneway 方法)时,该事务会被缓冲,直到远程进程解冻。如果缓冲区溢出,接收方应用进程可能会崩溃。此外,在应用进程解冻并处理缓冲的事务时,这些事务可能已经过时。

为避免应用因过时事件而过载或缓冲区溢出,您必须在接收方应用的进程处于冻结状态时暂停分派回调。

如需跟踪应用何时被冻结或解冻,请使用 IBinder.addFrozenStateChangeCallback:

Java

// The binder token of the remote process
IBinder binder = service.getBinder();

// Keep track of frozen state
AtomicBoolean remoteFrozen = new AtomicBoolean(false);

// Update remoteFrozen when the remote process freezes or unfreezes
binder.addFrozenStateChangeCallback(
    myExecutor,
    new IBinder.FrozenStateChangeCallback() {
        @Override
        public void onFrozenStateChanged(boolean isFrozen) {
            remoteFrozen.set(isFrozen);
        }
    });

// When dispatching callbacks to the remote process, pause dispatch if frozen:
if (!remoteFrozen.get()) {
    // dispatch callback to remote process
}

Kotlin

// The binder token of the remote process
val binder: IBinder = service.getBinder()

// Keep track of frozen state
val remoteFrozen = AtomicBoolean(false)

// Update remoteFrozen when the remote process freezes or unfreezes
binder.addFrozenStateChangeCallback(myExecutor) { isFrozen ->
    remoteFrozen.set(isFrozen)
}

// When dispatching callbacks to the remote process, pause dispatch if frozen:
if (!remoteFrozen.get()) {
    // dispatch callback to remote process
}

C++

对于使用 C++ Binder API 的平台代码:

#include <binder/Binder.h>
#include <binder/IBinder.h>

// The binder token of the remote process
android::sp<android::IBinder> binder = service->getBinder();

// Keep track of frozen state
std::atomic<bool> remoteFrozen = false;

// Define a callback class
class MyFrozenStateCallback : public android::IBinder::FrozenStateChangeCallback {
public:
    explicit MyFrozenStateCallback(std::atomic<bool>* frozenState) : mFrozenState(frozenState) {}
    void onFrozenStateChanged(bool isFrozen) override {
        mFrozenState->store(isFrozen);
    }
private:
    std::atomic<bool>* mFrozenState;
};

// Update remoteFrozen when the remote process freezes or unfreezes
if (binder != nullptr) {
    binder->addFrozenStateChangeCallback(android::sp<android::IBinder::FrozenStateChangeCallback>::make(
        new MyFrozenStateCallback(&remoteFrozen)));
}

// When dispatching callbacks to the remote process, pause dispatch if frozen:
if (!remoteFrozen.load()) {
    // dispatch callback to remote process
}

NDK

对于使用 NDK API(API 级别 37 及更高级别)的原生代码:

#include <android/binder_auto_utils.h>
#include <android/binder_ibinder.h>
#include <atomic>

// The binder token of the remote process
AIBinder* binder; // = ... get binder from elsewhere

// Keep track of frozen state
std::atomic<bool> remoteFrozen = false;

// Callback function for frozen state changes
void onFrozenStateChanged(void* cookie, bool frozen) {
    std::atomic<bool>* remoteFrozenPtr =
            static_cast<std::atomic<bool>*>(cookie);
    remoteFrozenPtr->store(frozen);
}

// Callback function for unlink (remote death)
void onBinderUnlinked(void* /*cookie*/) {
    // For the purpose of this example, this callback does nothing
}

// Create frozen state change callback
ndk::ScopedAIBinder_FrozenStateChangeCallback frozenStateChangeCallback(
        AIBinder_FrozenStateChangeCallback_new(
                onFrozenStateChanged, onBinderUnlinked));

// Register frozen state change callback
binder_status_t status = AIBinder_addFrozenStateChangeCallback(
        binder, frozenStateChangeCallback.get(), &remoteFrozen);
if (status != STATUS_OK) {
    // handle error, e.g. binder driver might not be available
}

// When dispatching callbacks to the remote process, pause dispatch if frozen:
if (!remoteFrozen.load()) {
    // dispatch callback to remote process
}

使用 RemoteCallbackList

RemoteCallbackList 类是一个辅助类,用于管理远程进程注册的 IInterface 回调列表。此类会自动处理 binder 终止通知,并提供用于处理对冻结应用的回调的选项。

构建 RemoteCallbackList 时,您可以指定冻结的被调用方政策:

  • FROZEN_CALLEE_POLICY_DROP:对冻结应用的回调会被静默丢弃。 如果应用被缓存时发生的事件对应用不重要(例如实时传感器事件),请使用此政策。
  • FROZEN_CALLEE_POLICY_ENQUEUE_MOST_RECENT:如果在应用处于冻结状态时广播了多个回调,则只有最新的回调会加入队列,并在应用解冻时传递。这对于基于状态的回调非常有用,因为只有最新的状态更新才重要,例如,向应用通知当前媒体音量的回调。
  • FROZEN_CALLEE_POLICY_ENQUEUE_ALL:应用处于冻结状态时广播的所有回调都会排队,并在应用解冻时传送。请谨慎使用此政策,因为如果加入队列的回调过多,可能会导致缓冲区溢出,或者导致过时事件累积。

以下示例展示了如何创建和使用 RemoteCallbackList 实例,该实例会丢弃对已冻结应用的回调:

Java

RemoteCallbackList<IMyCallbackInterface> callbacks =
        new RemoteCallbackList.Builder<IMyCallbackInterface>(
                        RemoteCallbackList.FROZEN_CALLEE_POLICY_DROP)
                .setExecutor(myExecutor)
                .build();

// Registering a callback:
callbacks.register(callback);

// Broadcasting to all registered callbacks:
callbacks.broadcast((callback) -> callback.onSomeEvent(eventData));

Kotlin

val callbacks =
    RemoteCallbackList.Builder<IMyCallbackInterface>(
        RemoteCallbackList.FROZEN_CALLEE_POLICY_DROP
    )
        .setExecutor(myExecutor)
        .build()

// Registering a callback:
callbacks.register(callback)

// Broadcasting to all registered callbacks:
callbacks.broadcast { callback -> callback.onSomeEvent(eventData) }

如果您使用 FROZEN_CALLEE_POLICY_DROP,则仅当托管回调的进程未冻结时,系统才会调用 callback.onSomeEvent()。

系统服务和应用互动

系统服务通常会使用 binder 与许多不同的应用进行交互。由于应用可以进入缓存和冻结状态,因此系统服务必须特别注意妥善处理这些交互,以帮助维护系统稳定性和性能。

系统服务已经需要处理应用进程因各种原因而被终止的情况。这包括停止代表它们工作,并且不尝试继续向已终止的进程传递回调。考虑应用被冻结的情况是这项现有监控职责的延伸。

通过系统服务跟踪应用状态

在 system_server 中运行或作为原生守护程序运行的系统服务也可以使用前面介绍的 API 来跟踪应用进程的重要性和冻结状态:

  • ActivityManager.addOnUidImportanceListener:系统服务可以注册监听器来跟踪 UID 重要性变化。当收到来自应用的 binder 调用或回调时,该服务可以使用 Binder.getCallingUid() 获取 UID,并将其与监听器跟踪的重要性状态相关联。这样,系统服务便可知道调用应用是否处于缓存状态。

  • IBinder.addFrozenStateChangeCallback:当系统服务从应用收到 binder 对象时(例如,作为回调注册的一部分),它应在该特定 IBinder 实例上注册 FrozenStateChangeCallback。当托管该 binder 的应用进程被冻结或解冻时,这会直接通知系统服务。

针对系统服务的建议

我们建议所有可能与应用交互的系统服务都跟踪与其通信的应用进程的缓存和冻结状态。否则,可能会导致:

  • 资源消耗:为已缓存且用户不可见的应用执行工作可能会浪费系统资源。
  • 应用崩溃:对冻结应用的同步 binder 调用会导致应用崩溃。 如果异步事务缓冲区溢出,对冻结应用的异步 binder 调用会导致崩溃。
  • 应用行为异常:解冻的应用会立即收到在冻结期间发送给它们的所有缓冲异步 binder 事务。应用可能会在冻结器中停留无限长的时间,因此缓冲的事务可能会非常过时。

系统服务通常使用 RemoteCallbackList 来管理远程回调并自动处理失效进程。如需处理冻结的应用,请按照使用 RemoteCallbackList 中的说明,应用冻结的被调用方政策,以扩展 RemoteCallbackList 的现有用法。