最近项目中遇到一个需求,实时监测手机是否接通电源,大概效果如下:
如果拔掉充电器上图中的对号就不显示
怎么实现呢,第一想到的就是使用广播来进行监听,代码如下:
/**
* 充电检测
*/
public class BatteryListener{
private Context mContext;
private BatteryBroadcastReceiver receiver;
private BatteryStateListener mBatteryStateListener;
public BatteryListener(Context context) {
mContext = context;
receiver = new BatteryBroadcastReceiver();
}
public void register(BatteryStateListener listener) {
mBatteryStateListener = listener;
if (receiver != null) {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
filter.addAction(Intent.ACTION_BATTERY_LOW);
filter.addAction(Intent.ACTION_BATTERY_OKAY);
filter.addAction(Intent.ACTION_POWER_CONNECTED);
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
mContext.registerReceiver(receiver, filter);
}
}
public void unregister() {
if (receiver != null) {
mContext.unregisterReceiver(receiver);
}
}
private class BatteryBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
String acyion = intent.getAction();
switch (acyion) {
case Intent.ACTION_BATTERY_CHANGED://电量发生改变
if (mBatteryStateListener != null) {
// Log.e("zhang", "BatteryBroadcastReceiver --> onReceive--> ACTION_BATTERY_CHANGED");
mBatteryStateListener.onStateChanged();
}
break;
case Intent.ACTION_BATTERY_LOW://电量低
if (mBatteryStateListener != null) {
// Log.e("zhang", "BatteryBroadcastReceiver --> onReceive--> ACTION_BATTERY_LOW");
mBatteryStateListener.onStateLow();
}
break;
case Intent.ACTION_BATTERY_OKAY://电量充满
if (mBatteryStateListener != null) {
// Log.e("zhang", "BatteryBroadcastReceiver --> onReceive--> ACTION_BATTERY_OKAY");
mBatteryStateListener.onStateOkay();
}
break;
case Intent.ACTION_POWER_CONNECTED://接通电源
if (mBatteryStateListener != null) {
// Log.e("zhang", "BatteryBroadcastReceiver --> onReceive--> ACTION_POWER_CONNECTED");
mBatteryStateListener.onStatePowerConnected();
}
break;
case Intent.ACTION_POWER_DISCONNECTED://拔出电源
if (mBatteryStateListener != null) {
// Log.e("zhang", "BatteryBroadcastReceiver --> onReceive--> ACTION_POWER_DISCONNECTED");
mBatteryStateListener.onStatePowerDisconnected();
}
break;
}
}
}
}
public interface BatteryStateListener {
public void onStateChanged();
public void onStateLow();
public void onStateOkay();
public void onStatePowerConnected();
public void onStatePowerDisconnected();
}
}
/**
* 使用
*/
BatteryListener listener = new BatteryListener(this);
listener.register(new BatteryListener.BatteryStateListener() {
@Override
public void onStateChanged() { //电量发生改变
}
@Override
public void onStateLow() { //电量低
}
@Override
public void onStateOkay() { //电量充满
}
@Override
public void onStatePowerConnected() { //接通电源
charge_true.setVisibility(View.VISIBLE);
}
@Override
public void onStatePowerDisconnected() { //拔出电源
charge_true.setVisibility(View.GONE);
}
});
以上就是全部的实现,特此写一篇帖子记录,方便以后使用,希望可以给遇到同样需求的同学带来帮助。
会不定时更新安卓相关知识,喜欢的给点一下关注,感谢大家支持!!
网友评论