业余时间写了一个小程序,怎么获取手机电池的当前电量
1:先看它的布局代码,有点简单layout/main.xml
"1.0" encoding= "utf-8"?>
"http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
      android:id="@+id/tvBatteryChanged"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="30dp"
  />
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:运行如图:
程序有点简单,业余时间玩玩,希望大家喜欢