Background
On a large app, that is very popular, I've noticed that when we close a foreground service, on a very specific group of devices (OnePlus devices: 6, 6T,A6000 and a few others) and Android versions (Android 9) , we got NPE:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
at android.os.Parcel.createException + 1956(Parcel.java:1956)
at android.os.Parcel.readException + 1918(Parcel.java:1918)
at android.os.Parcel.readException + 1868(Parcel.java:1868)
at android.app.IActivityManager$Stub$Proxy.setServiceForeground + 5111(IActivityManager.java:5111)
at android.app.Service.stopForeground + 724(Service.java:724)
at android.app.Service.stopForeground + 710(Service.java:710)
...
And the code that calls it is:
stopForeground(true) //crash here
stopSelf()
The problem
Since I don't have any of those devices, let alone Android 9 for them, I can't find the reason for this.
Since the app is so popular, and I see this issue exists only on those devices and Android versions, I suspect that indeed something is wrong only for them.
What I've found
Only thing I could do is to search for this issue over the Internet, but I couldn't find it.
The only similar thing is here, but it talks about Android O, and we didn't get even a single crash event there.
I know that sadly various manufacturers have applied a bad behavior that kills apps even if they are in the foreground (written about here), but I didn't think that this could cause a crash...
The questions
Is there anything I can do to prevent it? The other place mentioned to use a wakeLock. Would that help?
Maybe would using try-catch avoid this crash? But then what could happen? Would
stopSelf
alone make the service stop as usual? Or maybe I need to use try-catch on it as well?What is this exception anyway? I thought it would tell me about some invalid state, but instead I see NPE...