一、动态代码为广播添加action过滤条件。
PS:
BatteryReceiver batteryReceiver = new BatteryReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
intentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
registerReceiver(batteryReceiver,intentFilter);
二、介绍两个特殊的系统广播–电池电量和锁屏
1、电池电量
<intent-filter>
<action android:name="android.intent.action.BATTERY_OKAY"/>
<action android:name="android.intent.action.BATTERY_CHANGED"/>
<action android:name="android.intent.action.BATTERY_LOW"/>
</intent-filter>
switch (intent.getAction()){
case Intent.ACTION_BATTERY_OKAY:
Toast.makeText(context,"电量已恢复,可以使用",Toast.LENGTH_SHORT).show();
break;
case Intent.ACTION_BATTERY_CHANGED:
Bundle bundle = intent.getExtras();
//获取到当前电量
//level、scale源代码中获得
int current = bundle.getInt("level");
// 总电量
int total = bundle.getInt("scale");
StringBuilder builder =new StringBuilder();
builder.append("当前电量:"+current+",总电量:"+total);
//如果当前电量大于30%,可以刷机
// 否则提示电量低,不能操作
if(current * 1.0/total < 0.3){
builder.append("电量过低,不能进行刷机操作");
}else {
builder.append("电量充足,可以操作");
}
Toast.makeText(context,builder.toString(),Toast.LENGTH_SHORT).show();
break;
case Intent.ACTION_BATTERY_LOW:
Toast.makeText(context,"电量过低,需要充电",Toast.LENGTH_SHORT).show();
break;
}
2、锁屏
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action.SCREEN_OFF"/>
</intent-filter>