It's a very tricky question.The related code on Android Developer has a mistake.
Basically, you can learn how to detect it on this link:
https://developer.android.com/training/monitoring-device-state/battery-monitoring.html
You can detect whether it is charging or not charging and low battery or not by a broadcast receiver, using method OnReceive(Context context, Intent intent){}
However, there is a mistake in this link, for monitoring the significant changes.[Notice here, action name is android.intent.action.ACTION_BATTERY_LOW]
[1]
But let's see how it is described in Intent.
ACTION_BATTERY_LOW
Added in API level 1
String ACTION_BATTERY_LOW
Broadcast Action: Indicates low battery condition on the device. This broadcast corresponds to the "Low battery warning" system dialog.
This is a protected intent that can only be sent by the system.
Constant Value: "android.intent.action.BATTERY_LOW"
You can find this in Android Developers Intent.
In other words, a mistake happens here. It should be action.BATTERY_LOW instead of action.ACTION_BATTERY_LOW.So your code in AndroidManifest should be:
<receiver android:name=".receiver.BatteryLevelReceiver">
<intent-filter>
<action android:name="android.intent.action.BATTERY_LOW"/>
<!--instead of android.intent.action.ACTION_BATTERY_LOW-->
</intent-filter>
</receiver>
Also make sure you have your Receiver correct.
public class BatteryLevelReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "BAttery's dying!!", Toast.LENGTH_LONG).show();
Log.e("", "BATTERY LOW!!");
}
}
It's diffcult to debug or get Log on your laptop, the use of Toast might help.
Toast.makeText(context, "BAttery's dying!!", Toast.LENGTH_LONG).show();
//Toast.makeText(Context context, String str, Integer integer).show();
Hopefully it helps to solve you problem.