http://cf1.eoe.cn/android/jj01/01/ppt/14.pdf
http://blog.youkuaiyun.com/androidzhaoxiaogang/article/details/8579163
http://www.linuxidc.com/Linux/2013-07/87619.htm
Android程序中耗电最多的地方在以下几个方面 :
1、 大数据量的传输。
2、 不停的在网络间切换。
3、 解析大量的文本数据。
那么我们怎么样来改善一下我们的程序呢?
1、 在需要网络连接的程序中,首先检查网络连接是否正常,如果没有网络连接,那么就不需要执行相应的程序。
检查网络连接的方法如下:
- ConnectivityManager mConnectivity;
- TelephonyManager mTelephony;
- ……
- // 检查网络连接,如果无网络可用,就不需要进行连网操作等
- NetworkInfo info = mConnectivity.getActiveNetworkInfo();
- if (info == null ||
- !mConnectivity.getBackgroundDataSetting()) {
- return false;
- }
- //判断网络连接类型,只有在3G或wifi里进行一些数据更新。
- int netType = info.getType();
- int netSubtype = info.getSubtype();
- if (netType == ConnectivityManager.TYPE_WIFI) {
- return info.isConnected();
- } else if (netType == ConnectivityManager.TYPE_MOBILE
- && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
- && !mTelephony.isNetworkRoaming()) {
- return info.isConnected();
- } else {
- return false;
- }
-
很多人开发的程序后台都会一个service不停的去服务器上更新数据,在不更新数据的时候就让它sleep,这种方式是非常耗电的,通常情况下,我们可以使用AlarmManager来定时启动服务。如下所示,第30分钟执行一次。
AlarmManager am = (AlarmManager)-
context.getSystemService(Context.ALARM_SERVICE); -
Intent intent = new Intent(context, MyService.class); -
PendingIntent pendingIntent = -
PendingIntent.getService(context, 0, intent, 0); -
long interval = DateUtils.MINUTE_IN_MILLIS * 30; -
long firstWake = System.currentTimeMillis() + interval; -
am.setRepeating(AlarmManager.RTC,firstWake, interval, pendingIntent); -
- public void onCreate() {
- // Register for sticky broadcast and send default
- registerReceiver(mReceiver, mFilter);
- mHandler.sendEmptyMessageDelayed(MSG_BATT, 1000);
- }
- IntentFilter mFilter =
- new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
- BroadcastReceiver mReceiver = new BroadcastReceiver() {
- public void onReceive(Context context, Intent intent) {
- // Found sticky broadcast, so trigger update
- unregisterReceiver(mReceiver);
- mHandler.removeMessages(MSG_BATT);
- mHandler.obtainMessage(MSG_BATT, intent).sendToTarget();
- }
- };