http://blog.csdn.net/lee576/article/details/8099067
手机电量发生改变时,系统会对放发送Intent的Action为android.intent.action.BATTERY_CHANGED,这个可以在AndroidManifest.xml中配置
- <receiver android:name="BatteryReceiver" >
- <!-- 监听电池电量改变 -->
- <intent-filter>
- <action android:name="android.intent.action.BATTERY_CHANGED" />
- </intent-filter>
- </receiver>
<receiver android:name="BatteryReceiver" >
<!-- 监听电池电量改变 -->
<intent-filter>
<action android:name="android.intent.action.BATTERY_CHANGED" />
</intent-filter>
</receiver>
- package WangLi.Service.MonitorBattery;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.os.Bundle;
- import android.widget.Toast;
- public class BatteryReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- Bundle bundle = intent.getExtras();
- //获取当前电量
- int current = bundle.getInt("level");
- //获取总电量
- int total = bundle.getInt("scale");
- //如果当前电量小于总电量的15%
- if(current * 1.0 / total < 0.15)
- {
- Toast.makeText(context, "电量过低,请尽快充电", 5000).show();
- }
- }
- }
package WangLi.Service.MonitorBattery;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
//获取当前电量
int current = bundle.getInt("level");
//获取总电量
int total = bundle.getInt("scale");
//如果当前电量小于总电量的15%
if(current * 1.0 / total < 0.15)
{
Toast.makeText(context, "电量过低,请尽快充电", 5000).show();
}
}
}
注意这两行代码的使用
- //获取当前电量
- int current = bundle.getInt("level");
- //获取总电量
- int total = bundle.getInt("scale");