I have seen posts where it was mentioned registerReceiver
has to be called (not defined in manifest) to receive ACTION_BATTERY_LOW
intent.
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
//....
registerReceiver(new BatteryLevelReceiver(), new IntentFilter(
Intent.ACTION_BATTERY_LOW));
}
// .......
}
BroadcastReceiver
public class BatteryLevelReceiver extends BroadcastReceiver
{
private static final String TAG = BatteryLevelReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "onReceive");
}
}
I do not see the "onReceive" log statement in logcat. I am using emulator to simulate battery low state, using telnet 5554
and executing power capacity 10
. I do see the battery status changing in the emulator but no intent triggered.
Also if I have to call registerReceiver()
inside an activity and I do not call unregisterReceiver
on onStop
or onDestroy
, is it okay? If not okay, how will I register for a receiver to receive system intents even when my app is not in foreground? (Apart from using manifest).
You can register
ACTION_BATTERY_LOW
in the manifest - see my detailed answer here - you can't registerACTION_BATTERY_CHANGED
in the manifest.The reason you do not receive it is probably you forgot to declare your RECEIVER in the manifest
No. You should register in
onResume
and unregister ononPause
ALWAYS - afteronPause
is called your receiver WON'T receive anywayOnly in manifest
The key is to disable charging with the telnet command
If you then set the battery level to a low capacity
the intent will be triggered
You can add the following code in your manifest.
In your
BroadCastNotifier Class
You will recieve the log message
GOT LOW BATTERY WARNING
when your battery is low, also try this in your device.Although the above code might work the best way is not to use BroadCast for such actions, you can monitor the battery level as described here. You can determine your battery with the code below which is way easier.
make sure: 1. you are setting the "Charger connection" to "NONE" 2. That battery status is "Discharging"