检测手机电池状态的代码 您所在的位置:网站首页 手机电池测试代码 检测手机电池状态的代码

检测手机电池状态的代码

2024-07-17 19:16| 来源: 网络整理| 查看: 265

监控电池变化比较简单,但是充电时候要电量从当前电量增长到满状态,然后一直重复,后来发现将对应的ImageView的background指定到animation即可

1.需要多张电量图片

电量状态1 电量状态2 电量状态3 电量状态4

电量状态5 电量状态6

2.然后生成多个animation文件,分别是从状态1到状态6,状态2到状态6.。。。。。

    如:animation_battery_1.xml

Xml代码 复制代码 收藏代码                                        

   如:animation_battery_2.xml

Xml代码 复制代码 收藏代码                                  

3.在代码里面通过设置ivBattery.setBackgroundResource(batteryAnimation),其中batteryAnimation为animation文件

Java代码 复制代码 收藏代码 public class BatteryActivity extends Activity {        ImageView ivBattery;//电池电量      ImageView ivBatteryCharging;//充电中            TextView tvStatus;            @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);                    setContentView(R.layout.battery_charging);                    ivBattery = (ImageView)findViewById(R.id.iv_battry);          ivBatteryCharging = (ImageView)findViewById(R.id.iv_battry_charging);          tvStatus = (TextView)findViewById(R.id.tv_statues);                    registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));      }            @Override      protected void onDestroy() {          super.onDestroy();          unregisterReceiver(batteryReceiver);      }            private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {                    @Override          public void onReceive(Context context, Intent intent) {              if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){                  int level = intent.getIntExtra("level", 0);                  int scale = intent.getIntExtra("scale", 100);                  int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_NOT_CHARGING);                                    notifyBattery(level,scale,status);              }          }      };                  public void notifyBattery(int level,int scale,int status){                    int per = scale/6;          int batteryPic;//电量图片          int batteryAnimation;//电量动态增长          if(level


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有