首先我們來看看android手機的電量都主要消耗在了什麼地方:
顯而易見,大部分的電都消耗在了網路連接、GPS、感應器上了。簡單的說也就是主要在以下情況下耗電比較多: 1、 大資料量的傳輸。 2、 不停的在網路間切換。 3、 解析大量的文本資料。
那麼我們怎麼樣來改善一下我們的程式呢?
1、 在需要網路連接的程式中,首先檢查網路連接是否正常,如果沒有網路連接,那麼就不需要執行相應的程式。檢查網路連接的方法如下:
Java代碼:
- 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;
- }
複製代碼
2、 使用效率高的資料格式和解析方法。通過測試發現,目前主流的資料格式,使用樹形解析(如DOM)和流的方式解析(SAX)
3、 目前大部門網站都支援GZIP壓縮,所以在進行大資料量下載時,盡量使用GZIP方式下載。使用方法如下所示:
Java代碼:
- import java.util.zip.GZIPInputStream;
- HttpGet request = new HttpGet();
- HttpResponse resp = new DefaultHttpClient().execute(request);
- HttpEntity entity = response.getEntity();
- InputStream compressed = entity.getContent();
- InputStream rawData = new GZIPInputStream(compressed);
複製代碼
使用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代碼:
- 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);
複製代碼
最後一招,在運行你的程式前先檢查電量,電量太低,那麼就提示使用者充電之類的,哈哈!使用方法:
Java代碼:
- public void onCreate() {
- 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) {
- update unregisterReceiver(mReceiver);
- mHandler.removeMessages(MSG_BATT);
- mHandler.obtainMessage(MSG_BATT, intent).sendToTarget();
- }
- };
降低android應用耗電量
http://www.eoeandroid.com/thread-72478-1-1.html