手机电池电量应用

原理概述:

    手机电池电量的获取在应用程序的开发中也很常用,Android系统中手机电池电量发生变化的消息是通过Intent广播来实现的,常用的Intent的Action有  Intent.ACTION_BATTERY_CHANGED(电池电量发生改变时)、Intent.ACTION_BATTERY_LOW(电池电量达到下限时)、和Intent.ACTION_BATTERY_OKAY(电池电量从低恢复到高时)。

    当需要在程序中获取电池电量的信息时,需要为应用程序注册BroadcastReceiver组件,当特定的Action事件发生时,系统将会发出相应的广播,应用程序就可以通过BroadcastReceiver来接受广播,并进行相应的处理。

public class MainActivity extends Activity {
    private TextView tv;
    private BatteryReceiver receiver=null;//电池接收的广播服务
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_content2);
        Switch sw=(Switch) findViewById(R.id.switch1);
        tv = (TextView) findViewById(R.id.tv);
        receiver=new BatteryReceiver();//监听电池电量的广播
        sw.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //获取电池电量
                if(isChecked){
                    IntentFilter filter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
                    registerReceiver(receiver, filter);//注册BroadcastReceiver
                }else {//停止获取电池电量
                    unregisterReceiver(receiver);
                    tv.setText(null);
                }
            }
        });
    }
    private class BatteryReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            int current=intent.getExtras().getInt("level");//获得当前电量
            int total=intent.getExtras().getInt("scale");//获得总电量
            int percent=current*100/total;
            tv.setText("现在的电量是"+percent+"%。");
        }
    }
}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="电量:" />

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="打开"
        android:textOff="关闭"
         android:textSize="30sp"
        android:text="查询电量 " />

</LinearLayout>

注册文件:

<receiver android:name="com.ts.work.MainActivity.BatteryReceiver">
      <intent-filter >
           <action android:name="android.intent.action.BATTERY_CHANGED"/>
      </intent-filter>
</receiver>

效果图:

posted @ 2016-06-15 14:22  ts-android  阅读(161)  评论(0编辑  收藏  举报