您的位置:首页 > 移动开发 > Android开发

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

2011-11-23 09:46 676 查看
程序将通过注册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>


运行效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: