標籤:i++ 預設 複用 chmod gradle net pretty adl rip
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效能最佳化典例(二)