BroadcastReceiver监听电量变化_移动开发_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > 移动开发 > BroadcastReceiver监听电量变化

BroadcastReceiver监听电量变化

 2014/4/7 23:04:30  我是大嘴猴  博客园  我要评论(0)
  • 摘要:用BroadcastReceiver监听电量的变化,可以实现BroadcastReceiver接收电量变化的广播,然后获取电量百分比信息。BatteryChangedReceiver.javapublicclassBatteryChangedReceiverextendsBroadcastReceiver{privatestaticfinalStringTAG="BatteryChangedReceiver";@OverridepublicvoidonReceive
  • 标签:变化 监听

  用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+"%");

 

 

上一篇: 药药切克闹 黑眼豆豆主唱研发智能手表 下一篇: 没有下一篇了!
发表评论
用户名: 匿名