电池 电量 监控
引用:http://billhoo.blog.51cto.com/2337751/762776
引言
初学Andorid,学习了包括Activity、Service、AppWidget、Broadcast、Intent、Notification、XML布局、XML配置等基础知识之后,尝试着做一个小玩意儿——电池监控,期间也是阻挠多多,现在基本完成了,所以把自己的经验分享给大家,希望能通过我的文章让还不会的朋友少走弯路,也算是这个小玩意儿的一点贡献。
由于时间有限,bill假设读者已经具备并能基本使用上述基础知识,本文将只描述如何利用上述知识构建一个监控Android电池电量的小程序(若有相关知识不甚清楚,请查询Android SDK自带的document,官方文档是我们学习Android的一大利器),若有任何疑问或建议,欢迎留言提出,bill会很高兴和大家一起学习进步!
开发环境及Android平台版本
Eclipse helios
Android SDK 1.6
Android SDK 1.6 及以上模拟器或者Android SDK 1.6及以上Android X86 虚拟机或真机
功能描述
由于Android自带的系统电池图标并不能显示当前电量,给不少用户带来了不便,所以本程序将对此进行改进,简单实现对Android手机电量的实时监控,并在左上角状态栏显示实时电池电量的通知图标,若正在充电,则显示充电状态。为方便起见,还为本程序制作了一个AppWidget,成为一个简单的桌面小工具。
效果预览
充电效果
整体思路概览
①由于要显示电池图标,因此需要一组对应的小icon,程序算出当前电量之后,就在状态栏上显示对应的icon即可。本程序用到的icon已经提供在附件,下载后将里面的icons直接复制到res\drawable-hdpi中即可。
②由于电池更新是一个长期存在的过程,因此需要将我们的程序注册为系统服务,以便长期生存于Android系统中。
③服务不会自行启动,因此我们需要为自己的服务创建一个Activity,在第一次启动本程序的Activity时创建并启动我们的监控服务,之后的事便交由服务处理,Activity暂时未有太大作用(之后还可以在Activity中显示电池当前的各种基本属性等等,本文不作介绍),当然,我们也可以不要Activity,直接将我们的服务设置为开机启动即可,关于开机启动的事项已在【Android开机启动Activity或Service的方法】一文中详细描述,恕不赘述。
④为了方便起见,应该制作本程序的桌面小工具,也就用到了AppWidget方面的知识,稍后一一道来。
分而治之
小麻雀的心脏——电池监控服务MonitorService
我们将要看到的是这个小麻雀的心脏——电池监控服务,本服务自启动至停止,始终通过接受来自系统的广播ACTION_BATTERY_CHANGED(本广播指示电量发生了改变)来判断并显示当前电量。
下面是本Service的完整代码,我会在可能费解的地方批注,希望能帮助大家理解。
- package com.billhoo.study;
- import android.app.Notification; //通知,即显示在屏幕左上角的小图标
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.app.Service;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.BatteryManager;
- import android.os.IBinder;
- public class MonitorService extends Service {
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- @Override
- public void onStart(Intent intent, int startId) {
- // 定义电池电量更新广播的过滤器,只接受带有ACTION_BATTERRY_CHANGED事件的Intent
- IntentFilter batteryChangedReceiverFilter = new IntentFilter();
- batteryChangedReceiverFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
- // 向系统注册batteryChangedReceiver接收器,本接收器的实现见代码字段处
- registerReceiver(batteryChangedReceiver, batteryChangedReceiverFilter);
- // 实例化Notification通知的管理器,即字段notification manager
- notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- // 由于初始化本服务时系统可能没有发出ACTION_BATTERY_CHANGED广播,那么刚才注册的那个接收器将不会在本服务启动时被激活,这种情况下就无法显示当前电量,因此在这里添加一个匿名广播接收器。
- new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- int level = intent.getIntExtra("level", 0); //电池电量等级
- int scale = intent.getIntExtra("scale", 100); //电池满时百分比
- int status = intent.getIntExtra("status", 0); //电池状态
- // 若正在充电
- if (status == BatteryManager.BATTERY_STATUS_CHARGING)
- notification = getNotification(getChargingIcon(level * 100 / scale),
- "电池监控", System.currentTimeMillis(), "电池电量", "正在充电");
- else
- notification = getNotification(getStateIcon(level * 100 / scale),
- "电池监控", System.currentTimeMillis(), "电池电量", "请及时充电");
- //向系统发送此通知,为方便起见,通知ID简单设为0
- notifyManager.notify(0, notification);
- }
- };
- }
- @Override
- public void onDestroy() {
- //当本服务终止时,通过通知ID注销左上角的通知
- notifyManager.cancel(0);
- }
- // --------------------------------------私有方法------------------------------
- // 获得一个notification
- private Notification getNotification(int notificationIcon, String tickerText,
- long when, String contentTitle, String contentText) {
- // 定义该notification的扩展文本和intent
- Notification notification = new Notification(notificationIcon, tickerText,
- when);
- Context context = getApplicationContext();
- Intent notificationIntent = new Intent(context, BatteryInfo.class);
- PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
- notificationIntent, 0);
- notification.setLatestEventInfo(context, contentTitle, contentText,
- contentIntent);
- // 设置本状态出现在“正在进行”而非“通知”栏目,不允许用户清除状态图标
- notification.flags |= Notification.FLAG_ONGOING_EVENT;
- return notification;
- }
- // 获得对应的电池状态图标
- private int getStateIcon(int batteryHealth) {
- if (batteryHealth >= 0 || batteryHealth <= 100)
- return batteryStateIcons[batteryHealth]; //这里是为了方便起见而硬编码的资源数组,直接从R.java文件中提取的十六进制资源ID
- return R.drawable.stat_sys_battery_unknown;
- }
- // 获得对应的充电状态图标
- private int getChargingIcon(int batteryHealth) {
- if (batteryHealth >= 0 && batteryHealth < 5)
- return R.drawable.stat_sys_battery_charge_anim0;
- if (batteryHealth >= 5 && batteryHealth < 10)
- return R.drawable.stat_sys_battery_charge_anim01;
- if (batteryHealth >= 10 && batteryHealth < 15)
- return R.drawable.stat_sys_battery_charge_anim02;
- if (batteryHealth >= 15 && batteryHealth < 20)
- return R.drawable.stat_sys_battery_charge_anim03;
- if (batteryHealth >= 20 && batteryHealth < 25)
- return R.drawable.stat_sys_battery_charge_anim04;
- if (batteryHealth >= 25 && batteryHealth < 30)
- return R.drawable.stat_sys_battery_charge_anim05;
- if (batteryHealth >= 30 && batteryHealth < 35)
- return R.drawable.stat_sys_battery_charge_anim06;
- if (batteryHealth >= 35 && batteryHealth < 40)
- return R.drawable.stat_sys_battery_charge_anim07;
- if (batteryHealth >= 40 && batteryHealth < 45)
- return R.drawable.stat_sys_battery_charge_anim08;
- if (batteryHealth >= 45 && batteryHealth < 50)
- return R.drawable.stat_sys_battery_charge_anim09;
- if (batteryHealth >= 50 && batteryHealth < 55)
- return R.drawable.stat_sys_battery_charge_anim10;
- if (batteryHealth >= 55 && batteryHealth < 60)
- return R.drawable.stat_sys_battery_charge_anim11;
- if (batteryHealth >= 60 && batteryHealth < 65)
- return R.drawable.stat_sys_battery_charge_anim12;
- if (batteryHealth >= 65 && batteryHealth < 70)
- return R.drawable.stat_sys_battery_charge_anim13;
- if (batteryHealth >= 70 && batteryHealth < 75)
- return R.drawable.stat_sys_battery_charge_anim14;
- if (batteryHealth >= 75 && batteryHealth < 80)
- return R.drawable.stat_sys_battery_charge_anim15;
- if (batteryHealth >= 80 && batteryHealth < 85)
- return R.drawable.stat_sys_battery_charge_anim16;
- if (batteryHealth >= 85 && batteryHealth < 90)
- return R.drawable.stat_sys_battery_charge_anim17;
- if (batteryHealth >= 90 && batteryHealth < 95)
- return R.drawable.stat_sys_battery_charge_anim18;
- if (batteryHealth >= 95 && batteryHealth < 100)
- return R.drawable.stat_sys_battery_charge_anim19;
- if (batteryHealth == 100)
- return R.drawable.stat_sys_battery_charge_animfull;
- return R.drawable.stat_sys_battery_unknown;
- }
- // -------------------------------私有字段--------------------------------------
- private NotificationManager notifyManager = null;
- private Notification notification = null;
- //这里是为了方便起见而硬编码的icon资源数组,直接从R.java文件中提取的十六进制资源ID,本数组的0号元素0x7f020002表示资源stat_sys_battery_0.png(见附件),以后累加。不同配置的ID可能不同,请读者自行修改。
- private int batteryStateIcons[] = { 0x7f020002, 0x7f020003, 0x7f020004,
- 0x7f020005, 0x7f020006, 0x7f020007, 0x7f020008, 0x7f020009, 0x7f02000a,
- 0x7f02000b, 0x7f02000c, 0x7f02000d, 0x7f02000e, 0x7f02000f, 0x7f020010,
- 0x7f020011, 0x7f020012, 0x7f020013, 0x7f020014, 0x7f020015, 0x7f020016,
- 0x7f020017, 0x7f020018, 0x7f020019, 0x7f02001a, 0x7f02001b, 0x7f02001c,
- 0x7f02001d, 0x7f02001e, 0x7f02001f, 0x7f020020, 0x7f020021, 0x7f020022,
- 0x7f020023, 0x7f020024, 0x7f020025, 0x7f020026, 0x7f020027, 0x7f020028,
- 0x7f020029, 0x7f02002a, 0x7f02002b, 0x7f02002c, 0x7f02002d, 0x7f02002e,
- 0x7f02002f, 0x7f020030, 0x7f020031, 0x7f020032, 0x7f020033, 0x7f020034,
- 0x7f020035, 0x7f020036, 0x7f020037, 0x7f020038, 0x7f020039, 0x7f02003a,
- 0x7f02003b, 0x7f02003c, 0x7f02003d, 0x7f02003e, 0x7f02003f, 0x7f020040,
- 0x7f020041, 0x7f020042, 0x7f020043, 0x7f020044, 0x7f020045, 0x7f020046,
- 0x7f020047, 0x7f020048, 0x7f020049, 0x7f02004a, 0x7f02004b, 0x7f02004c,
- 0x7f02004d, 0x7f02004e, 0x7f02004f, 0x7f020050, 0x7f020051, 0x7f020052,
- 0x7f020053, 0x7f020054, 0x7f020055, 0x7f020056, 0x7f020057, 0x7f020058,
- 0x7f020059, 0x7f02005a, 0x7f02005b, 0x7f02005c, 0x7f02005d, 0x7f02005e,
- 0x7f02005f, 0x7f020060, 0x7f020061, 0x7f020062, 0x7f020063, 0x7f020064,
- 0x7f020065, 0x7f02007b };
- // 接受电池信息更新的广播
- private BroadcastReceiver batteryChangedReceiver = new BroadcastReceiver() {
- public void onReceive(Context context, Intent intent) {
- int level = intent.getIntExtra("level", 0);
- int scale = intent.getIntExtra("scale", 100);
- int status = intent.getIntExtra("status", 0);
- // 若正在充电
- if (status == BatteryManager.BATTERY_STATUS_CHARGING)
- notification = getNotification(getChargingIcon(level * 100 / scale),
- "Battery Monitor", System.currentTimeMillis(), "电池电量", "正在充电");
- else
- notification = getNotification(getStateIcon(level * 100 / scale),
- "Battery Monitor", System.currentTimeMillis(), "电池电量", "请及时充电");
- notifyManager.notify(0, notification);
- }
- };
- }
光有心,不跳怎么行?——BatteryMonitor
通过上面的服务,我们就能得到一个在左上角显示当前电量的通知图标。现在心脏倒是被我们大家轻而易举地造出来了,下一步当然是让它跳动起来!
首先,我们需要将MonitorService服务在系统配置文件中进行注册。
- <!-- service -->
- <service android:name=".MonitorService" android:enabled="true" />
然后,我们需要一个心脏起搏器——Activity(或者直接把本服务作为开机启动项,请见Bill的另一篇文章【Android开机启动Activity或Service的方法】),下面,我们将在一个Activity中启动MonitorService服务。
首先我们需要将这个Activity在AndroidManifest.xml中进行注册
- <!-- activity -->
- <activity android:name=".BatteryMonitor" android:label="@string/battery_monitor_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
然后,在BatteryMonitor.java中编码启动我们的MonitorService服务即可
- package com.billhoo.study;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- public class BatteryMonitor extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //启动电池监控服务
- startService(new Intent(this, MonitorService.class));
- }
- }
至此,我们的电池监控小程序已经初见成效,大家可以启动我们的Activity,看看左上角是不是出现了一个小电池图标,并显示着当前电量?
好了,下面来让我们的程序邪恶滴向用户的桌面进军吧!
麻雀虽小,五脏俱全——MonitorWidgetProvider,为麻雀穿上衣服
众所周知,Android用户会将自己喜爱的小程序放在桌面以便快速启动,当然我们就不能放过这个机会!
但是,仅凭我们的Activity还做不到这一点,难道我们应该期望用户在他的程序列表中长按我们的Activity,然后使出吃奶的劲儿把它扔在桌面上吗?不,他们通常长按桌面,然后轻点一个自己中意的Widget插件便能满足他们的需求。
因此,我们的监控程序也应该有自己的Widget,一来方便用户查看电池状态(仅凭左上角的通知有时候并不能满足用户的需求),二来方便用户随时启动本程序附带的电池详细数据报告(本功能并未在本文中实现)。
下面就让我们一起来实现这个Widget!
我们知道,Widget本身就是一个广播接收器(BroadcastReceiver),因此我们最初企图直接用这个Widget接受ACTION_BATTERY_CHANGED广播并作出反应,但却发现这个接收器并不会接受电池更新的广播(不论我们在配置文件中配置与否)。所以只能另寻出路,我们想到,可以使用一个单独的为本Widget服务的Service,该Service检测到电池电量更新后就更新桌面的Widget显示。于是便有以下Widget及其配套Service的实现。
首先,我们需要为自己的Widget创建一个配置文件,用于描述本Widget在桌面显示时是个什么样子。
- <!-- 项目路径\res\layout\monitor_widget_layout.xml -->
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="72dip"
- android:layout_height="72dip">
- <ImageView android:id="@+id/monitor_widget_view"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:src="@drawable/vertical_battery_unknown" />
- </LinearLayout>
- <!-- 项目路径\res\xml\monitor_widget_info.xml (xml文件夹是自行创建的)-->
- <?xml version="1.0" encoding="utf-8"?>
- <appwidget-providerxmlns:androidappwidget-providerxmlns:android="http://schemas.android.com/apk/res/android" android:initialLayout="@layout/monitor_widget_layout"
- android:minWidth="72dip" android:minHeight="72dip" />
然后我们需要在AndroidManifest.xml配置文件中注册我们的Widget
- <receiver android:name=".MonitorWidgetProvider">
- <intent-filter>
- <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
- <action android:name="android.intent.action.BATTERY_CHANGED" />
- </intent-filter>
- <meta-data android:name="android.appwidget.provider"
- android:resource="@xml/monitor_widget_info" />
- </receiver>
最后,我们需要编写本Widget的实现代码
- package com.billhoo.study;
- import android.appwidget.AppWidgetManager;
- import android.appwidget.AppWidgetProvider;
- import android.content.Context;
- import android.content.Intent;
- public class MonitorWidgetProvider extends AppWidgetProvider
- {
- //当Widget第一次被启动时,启动配套服务
- @Override
- public void onEnabled(Context context) {
- context.startService(new Intent(context,
- WidgetUpdateService.class));
- }
- //当Widget更新时,启动配套服务
- @Override
- public void onUpdate(Context context, AppWidgetManager
- appWidgetManager,
- int appWidgetIds[]) {
- super.onUpdate(context, appWidgetManager, appWidgetIds);
- context.startService(new Intent(context,
- WidgetUpdateService.class));
- }
- // 当桌面上这个widget的所有实体都被删除后,停止配套服务
- @Override
- public void onDisabled(Context context) {
- context.stopService(new Intent(context, WidgetUpdateService.class));
- }
- }
下面让我们来为这个Widget编写配套的Service。
首先在AndroidManifest.xml中注册这个服务。
- <service android:name=".WidgetUpdateService" android:enabled="true" />
然后,编写其JAVA实现代码
- package com.billhoo.study;
- import android.app.Service;
- import android.appwidget.AppWidgetManager;
- import android.content.BroadcastReceiver;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.BatteryManager;
- import android.os.IBinder;
- import android.widget.RemoteViews;
- //用以根据电池电量更新而刷新桌面Widget的服务
- public class WidgetUpdateService extends Service {
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- @Override
- public void onStart(Intent intent, int startId) {
- // 向系统注册电池电量更新广播,只接受带有ACTION_BATTERRY_CHANGED事件的Intent
- registerReceiver(this.bCR, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
- bCR = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- int level = intent.getIntExtra("level", 0);
- int scale = intent.getIntExtra("scale", 100);
- int status = intent.getIntExtra("status", 0);
- int batteryHealth = level * 100 / scale;
- int icon = 0;
- AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
- RemoteViews widgetView = new RemoteViews(context.getPackageName(),
- R.layout.monitor_widget_layout);
- // 若正在充电
- if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
- icon = getChargingIcon(batteryHealth);
- widgetView.setImageViewResource(R.id.monitor_widget_view, icon
- );
- } else
- widgetView.setImageViewResource(R.id.monitor_widget_view,
- getStateIcon(batteryHealth));
- widgetManager.updateAppWidget(new ComponentName(context,
- MonitorWidgetProvider.class), widgetView);
- }
- };
- }
- private BroadcastReceiver bCR = null;
- // 获取电池状态图标
- private int getStateIcon(int batteryHealth) {
- if (batteryHealth >= 0 || batteryHealth <= 100)
- return batteryStateIcon[batteryHealth / 5];
- return R.drawable.vertical_battery_unknown;
- }
- // 获得对应的充电状态图标
- private int getChargingIcon(int batteryHealth) {
- if (batteryHealth >= 0 && batteryHealth < 5)
- return R.drawable.vertical_charging_00;
- if (batteryHealth >= 5 && batteryHealth < 10)
- return R.drawable.vertical_charging_01;
- if (batteryHealth >= 10 && batteryHealth < 15)
- return R.drawable.vertical_charging_02;
- if (batteryHealth >= 15 && batteryHealth < 20)
- return R.drawable.vertical_charging_03;
- if (batteryHealth >= 20 && batteryHealth < 25)
- return R.drawable.vertical_charging_04;
- if (batteryHealth >= 25 && batteryHealth < 30)
- return R.drawable.vertical_charging_05;
- if (batteryHealth >= 30 && batteryHealth < 35)
- return R.drawable.vertical_charging_06;
- if (batteryHealth >= 35 && batteryHealth < 40)
- return R.drawable.vertical_charging_07;
- if (batteryHealth >= 40 && batteryHealth < 45)
- return R.drawable.vertical_charging_08;
- if (batteryHealth >= 45 && batteryHealth < 50)
- return R.drawable.vertical_charging_09;
- if (batteryHealth >= 50 && batteryHealth < 55)
- return R.drawable.vertical_charging_10;
- if (batteryHealth >= 55 && batteryHealth < 60)
- return R.drawable.vertical_charging_11;
- if (batteryHealth >= 60 && batteryHealth < 65)
- return R.drawable.vertical_charging_12;
- if (batteryHealth >= 65 && batteryHealth < 70)
- return R.drawable.vertical_charging_13;
- if (batteryHealth >= 70 && batteryHealth < 75)
- return R.drawable.vertical_charging_14;
- if (batteryHealth >= 75 && batteryHealth < 80)
- return R.drawable.vertical_charging_15;
- if (batteryHealth >= 80 && batteryHealth < 85)
- return R.drawable.vertical_charging_16;
- if (batteryHealth >= 85 && batteryHealth < 90)
- return R.drawable.vertical_charging_17;
- if (batteryHealth >= 90 && batteryHealth < 95)
- return R.drawable.vertical_charging_18;
- if (batteryHealth >= 95 && batteryHealth < 100)
- return R.drawable.vertical_charging_19;
- if (batteryHealth == 100)
- return R.drawable.vertical_battery_full;
- return R.drawable.stat_sys_battery_unknown;
- }
- private int batteryStateIcon[] = { 0x7f02007d, 0x7f02007e, 0x7f02007f,
- 0x7f020080, 0x7f020081, 0x7f020082, 0x7f020083, 0x7f020084, 0x7f020085,
- 0x7f020086, 0x7f020087, 0x7f020088, 0x7f020089, 0x7f02008a, 0x7f02008b,
- 0x7f02008c, 0x7f02008d, 0x7f02008e, 0x7f02008f, 0x7f020090, 0x7f020091 };
- }
至此,我们的电池电量监控程序也算告一段落,这样,我们就不需要在忍受android自带的电池图标了,何乐不为?
让麻雀自食其力——开机启动
不过,我们的小麻雀的确还有点天然呆!需要你主动去找它,而不是它主动为你服务!这个不是好事情,尤其是对于电池电量监控来说。因此,我们需要对它做最后的改造——开机启动。关于开机启动的详细步骤bill已经在【Android开机启动Activity或Service的方法】一文中详述,故恕我不再赘述。