微波EDA网,见证研发工程师的成长!
首页 > 通信和网络 > 通信网络技术文库 > Android 手机电池电量的应用

Android 手机电池电量的应用

时间:09-06 来源:互联网 点击:
原理概述:
手机电池电量的获取在应用程序的开发中也很常用,Android系统中手机电池电量发生变化的消息是通过Intent广播来实现的,常用的Intent的Action有 Intent.ACTION_BATTERY_CHANGED(电池电量发生改变时)、Intent.ACTION_BATTERY_LOW(电池电量达到下限时)、和Intent.ACTION_BATTERY_OKAY(电池电量从低恢复到高时)。
当需要在程序中获取电池电量的信息时,需要为应用程序注册BroadcastReceiver组件,当特定的Action事件发生时,系统将会发出相应的广播,应用程序就可以通过BroadcastReceiver来接受广播,并进行相应的处理。
main.xml布局文件

  1. android:orientation="vertical"
  2. android:layout_width="fill_parent"
  3. android:layout_height="fill_parent">
  4. android:layout_width="fill_parent"
  5. android:layout_height="wrap_content"
  6. android:textOn="停止获取电量信息"
  7. android:textOff="获取电量信息" />
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content" />

复制代码


BatteryActivity类

  1. package com.ljq.activity;

  2. import android.app.Activity;
  3. import android.content.BroadcastReceiver;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.IntentFilter;
  7. import android.os.Bundle;
  8. import android.widget.CompoundButton;
  9. import android.widget.TextView;
  10. import android.widget.ToggleButton;
  11. import android.widget.CompoundButton.OnCheckedChangeListener;

  12. public class BatteryActivity extends Activity {
  13. private ToggleButton tb=null;
  14. private TextView tv=null;
  15. private BatteryReceiver receiver=null;

  16. @Override
  17. public void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.main);

  20. receiver=new BatteryReceiver();
  21. tv=(TextView)findViewById(R.id.tv);
  22. tb=(ToggleButton)findViewById(R.id.tb);
  23. tb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
  24. public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
  25. //获取电池电量
  26. if(isChecked){
  27. IntentFilter filter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
  28. registerReceiver(receiver, filter);//注册BroadcastReceiver
  29. }else {
  30. //停止获取电池电量
  31. unregisterReceiver(receiver);
  32. tv.setText(null);
  33. }

  34. }
  35. });

  36. }

  37. private class BatteryReceiver extends BroadcastReceiver{
  38. @Override
  39. public void onReceive(Context context, Intent intent) {
  40. int current=intent.getExtras().getInt("level");//获得当前电量
  41. int total=intent.getExtras().getInt("scale");//获得总电量
  42. int percent=current*100/total;
  43. tv.setText("现在的电量是"+percent+"%。");
  44. }
  45. }

  46. }

复制代码

本文讲述了Android 手机电池电量的应用,希望本文能给读者带来灵感,帮助读者解决疑问,感谢阅读本文。更多安卓技术问题欢迎加群探讨:278744577,验证码:eec,不写验证不予通过哟~

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top