Android 电源系列小结s
package com.ritterliu.newBatteryWidget; import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.Window;
import android.widget.TextView; public class NewBatteryInfoActivity extends Activity{
/** 定义电池信息变量 */
private static int currentBatteryPlugged=0;
private static int currentBatteryStatus=0;
private static int currentBatteryLevel=0;
private static int currentBatteryHealth=0;
private static int currentBatteryTemperature=0;
private static int currentBatteryVoltage=0;
private static String currentBatteryTechnology=""; /** TextView 声明 */
private static TextView tvBatteryStatus;
private static TextView tvBatteryLevel;
private static TextView tvBatteryHealth;
private static TextView tvBatteryTemperature;
private static TextView tvBatteryVoltage;
private static TextView tvBatteryTechnology; /** 定义好字符串以备使用 */
private static String batteryStatus="电池状态: ";
private static String batteryLevel="电池电量: ";
private static String batteryHealth="电池健康: ";
private static String batteryTemperature="电池温度: ";
private static String batteryVoltage="电池电压: ";
private static String batteryTechnology="电池技术: "; private static String batteryStatusCharging="正在充电";
private static String batteryStatusDischarging="正在放电";
private static String batteryStatusFull="已充满";
private static String batteryStatusNotCharging="未在充电";
private static String batteryStatusUnknown="状态未知"; private static String batteryPluggedAC="(AC)";
private static String batteryPluggedUSB="(USB)"; private static String batteryHealthCold="过冷";
private static String batteryHealthDead="损坏";
private static String batteryHealthGood="良好";
private static String batteryHealthOverheat="过热";
private static String batteryHealthOverVoltage="过压";
private static String batteryHealthUnknown="未知";
private static String batteryHealthUnspecifiedFailure="未知的故障"; /** 提示Service启动标志位 */
private static boolean flag; /** 提示信息接收器 */
BroadcastReceiver infoReceiver; public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); //设置activity无标题
setContentView(R.layout.newlayout); //使用newlayout的布局 tvBatteryStatus=(TextView)findViewById(R.id.tvBatteryStatus);
tvBatteryLevel=(TextView)findViewById(R.id.tvBatteryLevel);
tvBatteryHealth=(TextView)findViewById(R.id.tvBatteryHealth);
tvBatteryTemperature=(TextView)findViewById(R.id.tvBatteryTemperature);
tvBatteryVoltage=(TextView)findViewById(R.id.tvBatteryVoltage);
tvBatteryTechnology=(TextView)findViewById(R.id.tvBatteryTechnology); flag=true; //提示service的标志位置为true infoReceiver=new BroadcastReceiver() //提示信息接收器的定义
{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
setText(); //收到intent,就及时修改TextView信息,使得Activity显示时,电池信息也能动态显示
}
}; /** 注册提示信息的intentFilter */
IntentFilter filter=new IntentFilter();
filter.addAction("com.ritterliu.newBatteryWidget");
registerReceiver(infoReceiver,filter); /** 启动提示service */
Intent startService=new Intent(this,updateService.class);
startService(startService); } /** 点击屏幕任意位置,关闭电池信息Activity */
public boolean onTouchEvent(MotionEvent event)
{
this.finish();
// onDestroy();
// System.exit(0);
return true;
} @Override
protected void onDestroy() {
// TODO Auto-generated method stub
flag=false;
unregisterReceiver(infoReceiver);
super.onDestroy();
} /** 及时动态修改Activity上文字信息的函数 */
public static void setText()
{
String plugState="";
switch(currentBatteryPlugged)
{
case 0:
plugState="";
break;
case 1:
plugState=batteryPluggedAC;
break;
case 2:
plugState=batteryPluggedUSB;
break;
default:
plugState="";
} switch(currentBatteryStatus)
{
case 1:
tvBatteryStatus.setText(batteryStatus+batteryStatusUnknown);
break;
case 2:
tvBatteryStatus.setText(batteryStatus+batteryStatusCharging+plugState);
break;
case 3:
tvBatteryStatus.setText(batteryStatus+batteryStatusDischarging);
break;
case 4:
tvBatteryStatus.setText(batteryStatus+batteryStatusNotCharging);
break;
case 5:
tvBatteryStatus.setText(batteryStatus+batteryStatusFull+plugState);
break;
default:
tvBatteryStatus.setText(batteryStatus+batteryStatusUnknown);
} tvBatteryLevel.setText(batteryLevel+String.valueOf(currentBatteryLevel)+"%"); switch(currentBatteryHealth)
{
case 1:
tvBatteryHealth.setText(batteryHealth+batteryHealthUnknown);
break;
case 2:
tvBatteryHealth.setText(batteryHealth+batteryHealthGood);
break;
case 3:
tvBatteryHealth.setText(batteryHealth+batteryHealthOverheat);
break;
case 4:
tvBatteryHealth.setText(batteryHealth+batteryHealthDead);
break;
case 5:
tvBatteryHealth.setText(batteryHealth+batteryHealthOverVoltage);
break;
case 6:
tvBatteryHealth.setText(batteryHealth+batteryHealthUnspecifiedFailure);
break;
case 7:
tvBatteryHealth.setText(batteryHealth+batteryHealthCold);
break;
default:
tvBatteryHealth.setText(batteryHealth+batteryHealthUnknown);
} tvBatteryTemperature.setText(batteryTemperature+currentBatteryTemperature/10f+"℃");
tvBatteryVoltage.setText(batteryVoltage+currentBatteryVoltage+"mv");
tvBatteryTechnology.setText(batteryTechnology+currentBatteryTechnology);
} /** 提示信息变化的service,约每隔一秒,就发送intent,
* 提醒activity更新电池信息,主要为了检测电池状态的变化,
* 例如连上充电时,状态会从“未在充电”变为“正在充电”
* 通过调用plugged方式,还能判断是AC方式充电还是USB方式充电
*/
public static class updateService extends Service{
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
} /** 定义得到电池信息的BroadcastReceiver,提取出关键信息,存入变量中 */
private BroadcastReceiver batteryReceiver=new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
currentBatteryStatus=intent.getIntExtra("status", 0);
currentBatteryLevel=intent.getIntExtra("level", 0);
currentBatteryHealth=intent.getIntExtra("health", 0);
currentBatteryTemperature=intent.getIntExtra("temperature",0);
currentBatteryVoltage=intent.getIntExtra("voltage",0);
currentBatteryTechnology=intent.getStringExtra("technology");
currentBatteryPlugged=intent.getIntExtra("plugged",0);
}
}; public void onStart(Intent intent,int startId)
{
registerReceiver(batteryReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));//注册BroadcastReceiver /** 启动一个线程,约每隔一秒就发送intent提醒Activity更新电池信息 */
new Thread()
{
public void run()
{
while(flag)
{
Intent sendInfoToActivity=new Intent();
sendInfoToActivity.setAction("com.ritterliu.newBatteryWidget");
sendBroadcast(sendInfoToActivity); try
{
Thread.sleep(1000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}.start();
super.onStart(intent, startId);
}
}
}
package com.ritterliu.newBatteryWidget; import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast; public class NewBatteryWidget extends AppWidgetProvider{ private static int currentBatteryLevel;
private static int currentBatteryStatus; private static boolean firstTimeToCreate=true; public void onUpdate(Context context,AppWidgetManager appWidgetManager,int[] appWidgetIds)
{
super.onUpdate(context, appWidgetManager, appWidgetIds); /** 启动自动更新电池信息的service */
context.startService(new Intent(context,updateService.class)); /** 为AppWidget设置点击事件的响应,启动显示电池信息详情的activity */
Intent startActivityIntent = new Intent(context,NewBatteryInfoActivity.class);
PendingIntent Pintent = PendingIntent.getActivity(context,0,startActivityIntent,0);
RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.newrelativelayout);
views.setOnClickPendingIntent(R.id.imageView,Pintent);
appWidgetManager.updateAppWidget(appWidgetIds,views); } /** 自动更新电池信息的service,通过AlarmManager实现定时不间断地发送电池信息 */
public static class updateService extends Service{
Bitmap bmp; //定义机器人图片
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
} /** 定义一个接收电池信息的broascastReceiver */ private BroadcastReceiver batteryReceiver=new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
currentBatteryLevel=intent.getIntExtra("level", 0);
currentBatteryStatus=intent.getIntExtra("status", 0);
} }; private BroadcastReceiver powerConnectedReceiver=new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
setViews();
}
}; private BroadcastReceiver powerDisconnectedReceiver=new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
setViews(); }
}; /** 设置Widget的显示 */
private void setViews()
{
/** 定义一个AppWidgetManager */
AppWidgetManager manager=AppWidgetManager.getInstance(this); /** 定义一个RemoteViews,实现对AppWidget界面控制 */
RemoteViews views=new RemoteViews(getPackageName(),R.layout.newrelativelayout); if(currentBatteryStatus==2||currentBatteryStatus==5) //当正在充电或充满电时,显示充电的图片
{
if(currentBatteryLevel>=95)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.jcharge);
}
else if(currentBatteryLevel>=85&& currentBatteryLevel<95)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.icharge);
}
else if(currentBatteryLevel>=75&& currentBatteryLevel<85)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.hcharge);
}
else if(currentBatteryLevel>=65&& currentBatteryLevel<75)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.gcharge);
}
else if(currentBatteryLevel>=55&& currentBatteryLevel<65)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.fcharge);
}
else if(currentBatteryLevel>=45&& currentBatteryLevel<55)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.echarge);
}
else if(currentBatteryLevel>=35&& currentBatteryLevel<45)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.dcharge);
}
else if(currentBatteryLevel>=25&& currentBatteryLevel<35)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.ccharge);
}
else if(currentBatteryLevel>=15&& currentBatteryLevel<25)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.bcharge);
}
else
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.acharge);
}
}
else //未在充电时,显示不在充电状态的系列图片
{
if(currentBatteryLevel>=95)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.j);
}
else if(currentBatteryLevel>=85&& currentBatteryLevel<95)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.i);
}
else if(currentBatteryLevel>=75&& currentBatteryLevel<85)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.h);
}
else if(currentBatteryLevel>=65&& currentBatteryLevel<75)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.g);
}
else if(currentBatteryLevel>=55&& currentBatteryLevel<65)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.f);
}
else if(currentBatteryLevel>=45&& currentBatteryLevel<55)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.e);
}
else if(currentBatteryLevel>=35&& currentBatteryLevel<45)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.d);
}
else if(currentBatteryLevel>=25&& currentBatteryLevel<35)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.c);
}
else if(currentBatteryLevel>=15&& currentBatteryLevel<25)
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.b);
}
else
{
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.a);
}
} /** 设置AppWidget上显示的图片和文字的内容 */
views.setImageViewBitmap(R.id.imageView,bmp);
views.setTextViewText(R.id.tv,currentBatteryLevel+"%"); ComponentName thisWidget=new ComponentName(this,NewBatteryWidget.class); /** 更新AppWidget */
manager.updateAppWidget(thisWidget, views); } public void onStart(Intent intent,int startId)
{
super.onStart(intent, startId); /** 注册接收器 */
registerReceiver(batteryReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); /** 增加了对于POWER_CONNECTED和DISCONNECTED事件的监听,
* 以实现充电时信息的动态变化,避免了原来需要依赖AlarmManager
* 每隔一秒发送检测信息来实现,节约了电量,用原来隔一秒更新的方法,
* 经过一夜测试,插件耗电量居然占到了8%,汗。。。
*
* */
registerReceiver(powerConnectedReceiver,new IntentFilter(Intent.ACTION_POWER_CONNECTED));
registerReceiver(powerDisconnectedReceiver,new IntentFilter(Intent.ACTION_POWER_DISCONNECTED )); /** 使用AlarmManager实现,第一次启动Widget时隔一秒立即更新,
* 以后均为一分钟发送一次更新提示信息,实现信息实时动态变化,
* 实现节电功能
* */
long now=System.currentTimeMillis();
long pause; if(firstTimeToCreate)
{
firstTimeToCreate=false;
pause=1000;
}
else
{
pause=1000*60*2;
} Intent alarmIntent=new Intent();
alarmIntent=intent; PendingIntent pendingIntent=PendingIntent.getService(this, 0, alarmIntent, 0);
AlarmManager alarm=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP,now+pause,pendingIntent); setViews(); }
}
}
Android 电源系列小结s的更多相关文章
- Android学习系列(37)--App调试内存泄露之Context篇(下)
接着<Android学习系列(36)--App调试内存泄露之Context篇(上)>继续分析. 5. AsyncTask对象 我N年前去盛大面过一次试,当时面试官极力推荐我使用AsyncT ...
- Android学习系列(15)--App列表之游标ListView(索引ListView)
游标ListView,提供索引标签,使用户能够快速定位列表项. 也可以叫索引ListView,有的人称也为Tweaked ListView,可能更形象些吧. 一看图啥都懂了: 1. ...
- Android学习系列(23)--App主界面实现
在上篇文章<Android学习系列(22)--App主界面比较>中我们浅略的分析了几个主界面布局,选了一个最大众化的经典布局.今天我们就这个经典布局,用代码具体的实现它. 1.预览图先看下 ...
- Android 开发系列教程之(一)Android基础知识
什么是Android Android一词最早是出现在法国作家维里耶德利尔·亚当1986年发表的<未来夏娃>这部科幻小说中,作者利尔·亚当将外表像人类的机器起名为Android,这就是And ...
- Android电源管理基础知识整理
前言 待机.睡眠与休眠的区别? Android开发者官网当中提到"idle states",该如何理解,这个状态会对设备及我们的程序造成何种影响? 进入Doze模式中的idle状态 ...
- Android拓展系列(11)--打造Windows下便携的Android源码阅读环境
因为EXT和NTFS格式的差异,我一直对于windows下阅读Android源码感到不满. 前几天,想把最新的android5.0的源码下下来研究一下,而平时日常使用的又是windows环境,于是专门 ...
- [转]Android Studio系列教程六--Gradle多渠道打包
转自:http://www.stormzhang.com/devtools/2015/01/15/android-studio-tutorial6/ Android Studio系列教程六--Grad ...
- Android UI系列-----时间、日期、Toasts和进度条Dialog
您可以通过点击 右下角 的按钮 来对文章内容作出评价, 也可以通过左下方的 关注按钮 来关注我的博客的最新动态. 如果文章内容对您有帮助, 不要忘记点击右下角的 推荐按钮 来支持一下哦 如果您对文章内 ...
- 【Android进阶系列教程】前言
起因 因为初学Android的时候还没有写博客的意识,现在Android的门是入了,正在进阶的道路上行走,但是就这一路也走了不少的弯路.我想,总得来说Android入门还是比较容易的,网络资源比较丰富 ...
随机推荐
- html系列教程--center dl dt dd div
<center> 标签:对其所包括的文本进行水平居中. <datalist> 标签:定义列表,与 input 元素配合使用该元素,来定义 input 可能的值 demo: &l ...
- PowerDesigner使用方法小结
PowerDesigner多用来进行数据库模型设计,具有SQL语句自动生成等功能.当然,也有不少缺点,比如团队分享. 一.设置PowerDesigner模型视图中数据表显示列 1.Tools-Disp ...
- WinForm DataGridView看似刷新的问题
昨天同事winform遇到一个问题, 窗体上有一个时间控件,和一堆文本,下拉控件,时间控件是每秒都在动态走的 窗体下发一个DataGridView 控件显示保存后的数据 保存的数据库是在另一台机器B上 ...
- 图片上传webuploader
/** * 基于jquery的图片上传控件 */!function ($) { "use strict"; //定义上传事件 var upImgEvent = { fileQueu ...
- java enum的用法
原始的常量定义: public static fianl MON=“Mon”; public static final TUE="Tue"; 语法(定义) 创建枚举类型要使用 en ...
- Linux下为何都是文件的理解
所谓“文件”,就是在我们的电脑中,以实现某种功能.或某个软件的部分功能为目的而定义的一个单位. Linux都是以文件的形式存在,当我们访问某个文件(Linux中的文件有目录,连接,普通文本),由于Li ...
- python相似模块用例(一)
一:threading VS Thread 众所周知,python是支持多线程的,而且是native的线程,其中threading是对Thread模块做了包装,可以更加方面的被使用,threading ...
- 2 kNN-K-Nearest Neighbors algorithm k邻近算法(二)
2.3 示例:手写识别系统 2.3 .1 准备数据:将图像转换为测试向量 训练样本:trainingDigits 2000个例子,每个数字大约200个样本 测试数据:testDigits 大约900个 ...
- mongodb or操作与连接池
mongodb # 类似于sql中的in或者or操作 mulites field query: db.cool.find({$or:[{field1:'val'},{'field2':'val'}-] ...
- Trafic
Dialogue 1 You took the wrong bus 你做错车了 A:Hi, I want to see the Terra Cotta Warriors in Xi'an. Coul ...