首先我们来看看android手机的电量都主要消耗在了什么地方:
显而易见,大部分的电都消耗在了网络连接、GPS、传感器上了。简单的说也就是主要在以下情况下耗电比较多:
1、 大数据量的传输。
2、 不停的在网络间切换。
3、 解析大量的文本数据。
那么我们怎么样来改善一下我们的程序呢?
1、 在需要网络连接的程序中,首先检查网络连接是否正常,如果没有网络连接,那么就不需要执行相应的程序。检查网络连接的方法如下:
Java代码:
1.
2. ConnectivityManager mConnectivity;TelephonyManager mTelephony; ……
3. // 检查网络连接,如果无网络可用,就不需要进行连网操作等
4. NetworkInfo info = mConnectivity.getActiveNetworkInfo();
5. if (info == null ||!mConnectivity.getBackgroundDataSetting()) {
6. return false;
7. }
8. //判断网络连接类型,只有在3G或wifi里进行一些数据更新。
9. int netType = info.getType();
10. int netSubtype = info.getSubtype();
11. if (netType == ConnectivityManager.TYPE_WIFI) {
12. return info.isConnected();
13. } else if (netType == ConnectivityManager.TYPE_MOBILE && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS && !mTelephony.isNetworkRoaming()) {
14. return info.isConnected();
15. } else {
16. return false;
17.
18. }
19.
复制代码
2、 使用效率高的数据格式和解析方法。通过测试发现,目前主流的数据格式,使用树形解析(如DOM)和流的方式解析(SAX)
3、 目前大部门网站都支持GZIP压缩,所以在进行大数据量下载时,尽量使用GZIP方式下载。使用方法如下所示:
Java代码:
1.
2. import java.util.zip.GZIPInputStream;
3.
4. HttpGet request = new HttpGet();
5. HttpResponse resp = new DefaultHttpClient().execute(request);
6. HttpEntity entity = response.getEntity();
7. InputStream compressed = entity.getContent();
8. InputStream rawData = new GZIPInputStream(compressed);
9.
复制代码
使用GZIP压缩方式下载数据,能减少网络流量,下图为使用GZIP方式获取包含1800个主题的RSS对比情况。
4、 其它一些优化方法:
回收java对象,特别是较大的java对像
XmlPullParserFactory and BitmapFactory
Matcher.reset(newString) for regex
StringBuilder.sentLength(0)
对定位要求不是太高的话尽量不要使用GPS定位,可能使用wifi和移动网络cell定位即可。GPS定位消耗的电量远远高于移动网络定位。
尽量不要使用浮点运算。
获取屏幕尺寸等信息可以使用缓存技术,不需要进行多次请求。
很多人开发的程序后台都会一个service不停的去服务器上更新数据,在不更新数据的时候就让它sleep,这种方式是非常耗电的,通常情况下,我们可以使用AlarmManager来定时启动服务。如下所示,第30分钟执行一次。
Java代码:
1.
2. AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
3. Intent intent = new Intent(context, MyService.class);
4. PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
5. long interval = DateUtils.MINUTE_IN_MILLIS * 30;
6. long firstWake = System.currentTimeMillis() + interval;am.setRepeating(AlarmManager.RTC,firstWake, interval, pendingIntent);
7.
复制代码
最后一招,在运行你的程序前先检查电量,电量太低,那么就提示用户充电之类的,哈哈!使用方法:
Java代码:
1.
2. public void onCreate() {
3. registerReceiver(mReceiver, mFilter);
4. mHandler.sendEmptyMessageDelayed(MSG_BATT, 1000);
5. }
6. IntentFilter mFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
7. BroadcastReceiver mReceiver = new BroadcastReceiver() {
8. public void onReceive(Context context, Intent intent) {
9. update unregisterReceiver(mReceiver);
10. mHandler.removeMessages(MSG_BATT);
11. mHandler.obtainMessage(MSG_BATT, intent).sendToTarget();
12. }
13.
14. };
降低android应用耗电量
http://www.eoeandroid.com/thread-72478-1-1.html