I am trying to check if power source is connected for Android devices. The following is the logic(based on a stackoverflow post by Commonsware),
Intent intent = context.registerReceiver(null, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
It mostly works fine. However from the Crashlytics reports, in certain cases the intent returned was null, causing the app to crash. I have never been able to reproduce it on my phones. Just wonder under what condition context.registerReceiver might return null? Is that because somehow another app was holding the system resource, or another thread in my app accessing the same resource at the time?
Thanks Ray
Just wonder under what condition context.registerReceiver might return null?
It will return null
if there has never been a broadcast of that Intent
. In this particular case, it might indicate a device that does not have a battery (e.g., Google TV/Android TV, OUYA) that therefore skips sending the broadcasts. Or it might indicate a somewhat broken firmware on the device (e.g., buggy ROM mod, engineering screwup at the device manufacturer).
Is that because somehow another app was holder the system resource, or another thread in my app accessing the same resource at the time?
No, those should not be a problem.