转自:http://www.blogjava.net/gaolei-xj/archive/2012/10/09/389262.html
原理概述:
手机电池电量的获取在应用程序的开发中也很常用,Android系统中手机电池电量发生变化的消息是通过Intent广播来实现的,常用的Intent的Action有 Intent.ACTION_BATTERY_CHANGED(电池电量发生改变时)、Intent.ACTION_BATTERY_LOW(电池电量达到下限时)、和Intent.ACTION_BATTERY_OKAY(电池电量从低恢复到高时)。
当需要在程序中获取电池电量的信息时,需要为应用程序注册BroadcastReceiver组件,当特定的Action事件发生时,系统将会发出相应的广播,应用程序就可以通过BroadcastReceiver来接受广播,并进行相应的处理。
LinearLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="取得电池电量" />
</LinearLayout>
MainActivity
package org.gl.demo;
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 MainActivity extends Activity {
private Button button = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new BatteryClickListener());
}
private class BatteryClickListener implements OnClickListener {
@Override
public void onClick(View v) {
BatteryBroadcastReceiver receiver = new BatteryBroadcastReceiver();
IntentFilter filter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED);
MainActivity.this.registerReceiver(receiver, filter);
}
}
}
BatteryBroadcastReceiver
package org.gl.demo;
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 BatteryBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
// 获得当前电量
int current = intent.getIntExtra("level", 0);
// 获取总电量
int total = intent.getIntExtra("scale", 0);
Dialog dialog = new AlertDialog.Builder(context)
.setTitle("电池电量")
.setMessage(
"电池电量为:" + String.valueOf(current * 100 / total)
+ "%")
.setNegativeButton("关闭",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
}
}).create();
dialog.show();
}
}
}