前言
什么是靜態(tài)代碼檢測?
靜態(tài)代碼檢測是不運(yùn)行代碼的前提下,利用預(yù)先設(shè)定好的規(guī)則對(duì)程序進(jìn)行分析,發(fā)現(xiàn)潛在問題。檢測工具價(jià)值度主要體現(xiàn)在檢測規(guī)則的數(shù)量和檢測精確度兩個(gè)方面。編譯器進(jìn)行編譯的過程中會(huì)檢測程序中的"硬傷",給出錯(cuò)誤和警告,靜態(tài)代碼檢測工作原理和編譯器相似,規(guī)則更嚴(yán)苛。
靜態(tài)代碼分析可以在開發(fā)過程中盡早的幫助團(tuán)隊(duì)發(fā)現(xiàn)潛在的問題和風(fēng)險(xiǎn),提高代碼質(zhì)量。關(guān)于java的靜態(tài)檢測工具可以參考下面鏈接:
https://www.ibm.com/developerworks/cn/java/j-lo-statictest-tools/
Android Studio逐漸替代Eclipse 成為Android開發(fā)首選IDE,一起來挖掘下Studio中靜態(tài)檢測的使用。
1. 前身:Eclipse ADT 工具Lint
功能入口:
右鍵Android項(xiàng)目--Android Tools--Run Lint:Check for Common Error
unused 資源:
The resource R.string.ok appears to be unused
The resource R.drawable.goback appears to be unused
布局問題:
Avoid using "px" as units; use "dp" instead
This RelativeLayout layout or its LinearLayout parent is useless
2. Android Studio中的Analyze
功能入口:
a.導(dǎo)航欄--Analyze--Inspact Code
b.項(xiàng)目頂層目錄--右鍵--Analyze--Inspact Code
Inspact Code 結(jié)果展示(啊啊!這么多問題啊,大部分是真實(shí)存在的問題)

2.1 問題分類
在官方文檔沒有找到對(duì)應(yīng)的文檔介紹,有找到的同學(xué)可以告訴我一下。
再上圖中點(diǎn)擊左側(cè)工具欄中的“設(shè)置”圖標(biāo),檢測規(guī)則好多啊,分類就這么一大排。

2.2 Android

舉例:
Missing JNI function
在java代碼中定義了native方法,但是沒有找到對(duì)應(yīng)的native實(shí)現(xiàn)
2.3 Android Lint

這個(gè)部分很多規(guī)則是從歷史版本繼承來的
舉例:
Handler reference leaks
Handler作為內(nèi)部類時(shí),會(huì)持有外部類的引用,可能會(huì)出現(xiàn)內(nèi)存泄露的風(fēng)險(xiǎn)
Handler reference leaks Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.

使用了SD卡路徑硬編碼
private static final String AUDIO_FILE = "/sdcard/harry/reult/audio.txt";
修改建議是
Environment.getExternalStorageDirectory().getPath()
Unused resources——沒有使用的資源
開發(fā)過程中有資源沒有使用,白白的浪費(fèi)資源,使Apk包變大,程序構(gòu)建變慢。現(xiàn)在Android 開發(fā)大家不太在意這些問題,早在幾年前Java ME的時(shí)代,整個(gè)安裝包只有幾百K,產(chǎn)品上線前此項(xiàng)檢測很嚴(yán)格。
The resource R.drawable.button_bg appears to be unused
Using dp instead of sp for text sizes——字體大小使用sp
當(dāng)然硬要使用sp也沒什么的只要UI在各個(gè)分辨率上展示ok就行。
PerFomance issues
代碼中有些無用的語句,浪費(fèi)性能。
比如我的代碼里寫了如下代碼:其中g(shù)etName()方法的返回值已經(jīng)是String類型了。
temp.getName().toString()
Use of 'java.lang.reflect'
使用java反射機(jī)制,被認(rèn)為是不安全的、低效的。
Object allocation in loop
在循環(huán)體內(nèi)new 對(duì)象可能會(huì)造成內(nèi)存泄露和性能問題。
總結(jié)
Android Studio中的靜態(tài)代碼檢測面很廣,規(guī)則很豐富。一起慢慢挖掘使用吧。