BroadcastReceiver监听电量变化
用BroadcastReceiver监听电量的变化,可以实现BroadcastReceiver接收电量变化的广播,然后获取电量百分比信息。
BatteryChangedReceiver.java
public class BatteryChangedReceiver extends BroadcastReceiver{ private static final String TAG="BatteryChangedReceiver"; @Override public void onReceive(Context context,Intent intent){ int currLevel=intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);//当前电量 int total=intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);//总电量 int percent=currLevel*100/total; Log.i(TAG,"battery:"+percent+"%"); } }
在清单文件中注册广播接收者以及要拦截的Action:
<receiver android:name=".BatteryChangedReceiver"> <intent-filter> <action android:name="android.intent.action.BATTERY_CHANGED"/> </intent-filter> </receiver>
有些时候,我们需要立即获取电量,而不是等电量变化的广播,可以通过下面的方式:
Intent batteryIntent=getApplicationContext().registerReceiver(null,new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int currLevel=batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL,0); int total=batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE,1); int percent=currLevel*100/total; Log.i("battery","battery:"+percent+"%");