PhoneStateListener 超过 Android 11 上允许的注册侦听器数量

PhoneStateListener is exceeding the number of permissible registered listeners on Android 11

我有一个 Android 应用程序,其中包括一个后台服务(通常在设备启动时启动)和一个 activity 提供 UI。有时,在 Android 11 台设备上,后台服务在尝试启动 activity 时抛出以下异常:

java.lang.RuntimeException: Unable to start service com.me.myapp.MyService@97e474c with Intent { cmp=com.me.myapp/.MyService }: java.lang.IllegalStateException: Pid 12345 has exceeded the number of permissible registered listeners. Ignoring request to add.

应用程序编译为API30,目标为API28。如果用户请求关闭后台服务,此时会注销监听器。它已经安装了数万次,并且已经流通了几年,相关代码没有改变:

public int onStartCommand(Intent in, int flags, int startId) {
    super.onStartCommand(in, flags, startId);
    signalStrengthListener = new SignalStrengthListener();

    // **the line below is flagged as causing the exception**
    ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).listen(signalStrengthListener,
        SignalStrengthListener.LISTEN_SIGNAL_STRENGTHS | SignalStrengthListener.LISTEN_SERVICE_STATE |
        SignalStrengthListener.LISTEN_CALL_STATE | SignalStrengthListener.LISTEN_DATA_ACTIVITY |
        SignalStrengthListener.LISTEN_DATA_CONNECTION_STATE);

除了它似乎仅限于 Android 11,并且只有当后台服务已经 运行 一段时间(即不是从头启动应用程序时)。该服务不会注册任何其他正在进行的侦听器。 API 30 似乎改变了一些行为,但我找不到任何对它的引用。我该如何解决这个问题?

Perhaps this code should be in onCreate(), not onStartCommand(), since the latter can be called more than once in the lifetime of the service.

SignalStrengthListener 构造函数的初始化移动到 onCreate() 确实解决了这个问题。 CommonsWare 正确地注意到 onStartCommand() 可以被多次调用,这最终导致了异常。

应该注意的是,我的 .listen 方法的实现在移出 onStartCommand() 时无法正常运行。

我通过取消侦听器来修复它:

@Override
public void onDestroy() {
    super.onDestroy();
    if (myListener != null) {
        telephonyManager.listen(myListener, PhoneStateListener.LISTEN_NONE);
        myListener = null;
    }
}