Android系列实例之:手机电池还剩多少

程序将通过注册BroadcastReceiver时设置的IntentFilter来捕捉系统发出的Intent.ACTION_BATTERY_CHANGED这个Action,再以此取得手机电池的计量结果
status(int类型)状态,定义值是BatteryManager.BATTERY_STATUS_XXX。
health(int类型)健康,定义值是BatteryManager.BATTERY_HEALTH_XXX。
present(boolean类型)
level(int类型)电池剩余容量
scale(int类型)电池最大值。通常为100。
icon-small(int类型)图标ID。
temperature(int类型)温度,0.1度单位。
例如表示197的时候,意思为19.7度。
technology(String类型)电池类型
例如,Li-ion等等。


Activity

package org.newboy.bat;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
	private Button buttonBattery; // 按钮

	private BroadcastReceiver mBatReceiver = new BroadcastReceiver() {
		int level; // 电池还剩多少
		int scale; // 总容量

		@Override
		public void onReceive(Context context, Intent intent) {
			// 得到相应的action
			String action = intent.getAction();
			if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
				// 电池剩余容量
				level = intent.getIntExtra("level", 0);
				// 电池最大值
				scale = intent.getIntExtra("scale", 100);
				// 显示电池信息
				AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
				builder.setTitle("电池信息").setMessage("电池还剩" + String.valueOf(level * 100 / scale) + "%");
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 点按钮取消广播的接收
						unregisterReceiver(mBatReceiver);
					}
				});
				builder.show();
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		buttonBattery = (Button) findViewById(R.id.buttonBattery);

		buttonBattery.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 通过代码注册广播
				registerReceiver(mBatReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
			}
		});
	}
}

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:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="@string/hello"
		android:layout_margin="2dip" />
	<Button android:text="显示电量" android:id="@+id/buttonBattery"
		android:layout_height="wrap_content" android:layout_width="match_parent"
		android:layout_margin="2dip"></Button>
</LinearLayout>

运行效果:


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值