[转]有效控制Android应用程序的耗电量
来源:http://mobile.51cto.com/android-229128.htm
51CTO在对尚邮架构师的访谈中曾经探讨过移动开发是否要重视移动终端软件的耗电问题,答案是显而易见的!那么如何才能降低Android应用程序的耗电量呢?今天再一次回顾了一下09年Google IO大会Jeffrey Sharkey的演讲(Coding for Life — Battery Life, That Is),同时也讲一下应该如何有效地控制耗电量问题。
首先我们来看看Android手机的电量都主要消耗在了什么地方:
显而易见,大部分的电都消耗在了网络连接、GPS、传感器上了。
简单的说也就是主要在以下情况下耗电比较多:
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; }
import java.util.zip.GZIPInputStream; HttpGet request = new HttpGet("http://example.com/gzipcontent"); HttpResponse resp = new DefaultHttpClient().execute(request); HttpEntity entity = response.getEntity(); InputStream compressed = entity.getContent(); InputStream rawData = new GZIPInputStream(compressed);
XmlPullParserFactory and BitmapFactory Matcher.reset(newString) for regex StringBuilder.sentLength(0)
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(); } };