Android性能優化典例(二)
1、使用 Maven 依賴方案取代使用導入jar包方案
假設項目中須要用到第三方jar包。經常使用的做法是去網上下載後然後放入libs目錄,再加入到項目依賴,只是,在Android Studio已經不推薦使用這套做法了,由於假設jar有更新。那麽每次都要去下載最新版本號然後刪除歷史依賴再加入新版本號的依賴,這樣做非常繁瑣。而在Android Studio中,這個問題使用Maven已經非常好的攻克了,由於AS中默認的是jcenter中央庫,而jcenter默認會同步Maven中央庫,所以我們能夠使用Gradle來加入依賴來取代之前的做法,比如:
dependencies { compile ‘com.android.support:appcompat-v7:22.+‘ compile ‘com.squareup.okhttp:okhttp:2.0.+‘ compile ‘com.android.support:recyclerview-v7:22.+‘ compile ‘com.android.support:cardview-v7:22.2.+‘ }
我們這樣使用。就指定了一個版本號範圍。當構建項目時候會自己主動從Maven庫中獲取指定範圍的最新版本號的jar包資源
2、避免深層次的布局結構(最多不要超過5層)
復雜的結構能夠考慮用相對布局
3、將同樣控件的同樣屬性抽取出來為一個style
比如:
假如有若幹個Button,而Button的樣式都是統一的,這時候我們能夠將Button的字體大小、顏色、背景色、字體類型等抽取出來放在一個style中,供多個Button復用,如:
<style name="MyButton" parent="Base.Widget.AppCompat.Button">
<item name="android:textSize">16sp</item>
<item name="android:textColor">#ffffff</item>
<item name="android:background">#202020</item>
<item name="android:typeface">sans</item>
</style>
layout布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Button
style="@style/MyButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Space
android:layout_width="match_parent"
android:layout_height="10dp" />
<Button
style="@style/MyButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/action_settings" />
<Space
android:layout_width="match_parent"
android:layout_height="10dp" />
<Button
style="@style/MyButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name" />
</LinearLayout>
效果:
能夠看到這三個Button的樣式都一樣。復用了同樣的style
4、慎用AsyncTask,使用網絡請求框架(Volley、OkHttp)取代
關於AsyncTask在異步網絡請求方面用的非常多,由於它使用起來比較輕量。可是關於AsyncTask也存在內存泄漏和結果丟失等問題。以下一起來看看:
1、內存泄漏
假設在Activity中使用AsyncTask以匿名內部類的方式請求網絡。由於AsyncTask的生命周期能夠比Activity的長(由於請求網絡數據是比較耗時的),AsyncTask內部類持有Activity的引用的話,假設還在請求網絡時就關閉了Activity,那麽將導致Activity對象將無法回收,進而產生內存泄漏
2、結果丟失
假如Activity的launchMode是默認或者是標準的,那麽當AsyncTask在請求網絡數據時把屏幕旋轉了,那麽將會又一次創建一個新的Activity,又由於還在執行的AsyncTask持有之前Activity的引用,那麽將導致onPostExecute()方法不起不論什麽作用,請求獲得的數據不能載入到新的Activity上,並且也將導致內存泄漏
3、串行和並行多版本號不一致
AsyncTask在1.6之前為串行,在1.6-2.3為並行,在3.0之後又改為串行。在3.0之後盡管能夠通過代碼來改變默認的串行為並行。可是又是一個繁瑣的操作
Android性能優化典例(二)