手机服务
14.1. BatteryManager(电池管理)
电池电量信息的Action
实例:取得电池电量信息
以对话框形式将电池电量广播出去:
package com.example.batteryproject; import android.app.AlertDialog; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; public class BatteryBroadcastReceive extends BroadcastReceiver { @Override public void onReceive(Context ctx, Intent intent) { // 接收广播 if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) { // 判断Action int level = intent.getIntExtra("level", 0); // 取得电池剩余容量 int scale = intent.getIntExtra("scale", 100); // 取得电池总量 Dialog dialog = new AlertDialog.Builder(ctx) // 创建对话框 .setTitle("电池电量") // 设置标题 .setMessage("电池电量为:" + String.valueOf(level * 100 / scale)+ "%") // 设置信息 .setNegativeButton("关闭", // 设置取消按钮 new DialogInterface.OnClickListener() { // 设置监听操作 public void onClick(DialogInterface dialog, int whichButton) { } }) // 显示信息 .create(); // 创建Dialog dialog.show(); // 显示对话框 } } } |
通过Activity启动广播:
package com.example.batteryproject; import android.app.Activity; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class BatteryActivity extends Activity { private Button but = null; @Override public void |