I have an Android app that includes a background service (that typically launches at device startup) and an activity that provides a UI. Occasionally, on Android 11 devices, the background service is throwing the following exception when trying to launch the 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.
The app is compiled with API 30, targeting API 28. If the user requests to shut down the background service, listeners are unregistered at that time. It has tens of thousands of installs and has been in circulation for several years with no changes to the pertinent code:
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);
I am unable to identify exactly what circumstances trigger this exception other than it appears to be limited to Android 11, and only occurs if the background service has been running for awhile (i.e. not when launching the app from scratch). The service does not register any other ongoing listeners. It appears that some behavior has changed with API 30, but I cannot find any references to it. How can I resolve this issue?