Android 显示手机电池的当前电量

业余时间写了一个小程序,怎么获取手机电池的当前电量
1:先看它的布局代码,有点简单layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
  <TextView
    android:id="@+id/tvBatteryChanged"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="30dp"
  />
</LinearLayout>
2:功能代码BatteryActivity.java
package com.android.test;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

public class BatteryActivity extends Activity {
    
  private TextView tvBatteryChanged;
  
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                
                tvBatteryChanged = (TextView)findViewById(R.id.tvBatteryChanged);
                //注册一个接受广播类型
                registerReceiver(batteryChangedReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        }
        
        //接受广播
        private BroadcastReceiver batteryChangedReceiver = new BroadcastReceiver() {

    public void onReceive(Context context, Intent intent) {
      if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
        int level = intent.getIntExtra("level", 0);
        int scale = intent.getIntExtra("scale", 100);
        tvBatteryChanged.setText("电池电量:" + (level * 100 / scale) + "%");
      }
    }  
        };
}
3:运行如图:
Android 显示手机电池的当前电量
程序有点简单,业余时间玩玩,希望大家喜欢Android 显示手机电池的当前电量









本文转自 Art_Hero 51CTO博客,原文链接:http://blog.51cto.com/curran/524985,如需转载请自行联系原作者
上一篇:黑客如何操控你的手机?一段超声波就够了


下一篇:HTML5手机端弹窗、提示框、loading加载(多功能xwPop弹窗升级版)