在當下的java的使用中,annotations已經被廣泛運用,來提升開發效率。在android中,主要是幫助開發者處理一些前後臺任務、rest 服務、應用類、代碼片段等,讓開發者專注於真正重要的東西。
(一)如何使用android annotations
具體使用方法請參看此文。
(二)使用範例
/**
* android annotations範例
*
* @author peter_wang
* @create-time 2014-9-13 下午7:40:56
*/
// 設置Activity的layout佈局文件
@EActivity(R.layout.activity_http_request)
public class HttpRequestActivity
extends Activity {
// 等同findviewById,名字默認是id名字
@ViewById
TextView tv_response_main;
//string資源文件信息
@StringRes(R.string.hello_world)
String mHelloWorld;
// 執行完oncreate後的動作
@AfterViews
void init() {
tv_response_main.setText(mHelloWorld);
}
// 點擊事件,tv_response_main代表點擊的觸發View對象id
@Click
void tv_response_mainClicked() {
getHttpData();
}
// 後臺執行線程
@Background
void getHttpData() {
try {
// 得到HttpClient對象
HttpClient getClient = new DefaultHttpClient();
// 得到HttpGet對象
HttpGet request = new HttpGet("http://192.168.140.1:8080/SimpleServer/servlet/PayServlet?id=1");
// 客戶端使用GET方式執行請教,獲得服務器端的迴應response
HttpResponse response = getClient.execute(request);
// 判斷請求是否成功
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 獲得輸入流
InputStreamReader inStrem = new InputStreamReader(response.getEntity().getContent());
BufferedReader br = new BufferedReader(inStrem);
StringBuilder sb = new StringBuilder();
String readLine = null;
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
}
setHttpDataUI(sb.toString());
// 關閉輸入流
inStrem.close();
}
else {
}
}
catch (Exception e) {
e.printStackTrace();
}
}
// 線程中更新UI
@UiThread
void setHttpDataUI(String data) {
tv_response_main.setText(data);
}
}
(三)工作原理
android annotations源於java annotations,簡單瞭解java annotations可以看這篇文章。
java annotations中包含三種類型:SourceCode、Class、Runtime。
android annotations是SourceCode類型,利用Java Annotation Processing Tool (APT) 在編譯源文件(*.java)之前,通過註解處理器(AnnotationProcessor)解釋並處理源文件中的註解,生成 一些新的源文件,APT也會對新生成源文件進行編譯,直到沒有新的文件生成。新生成的源文件在apt_generated文件夾中。
編譯前
package com.some.company;
@EActivity
public class MyActivity extends Activity {
// ...
}
編譯後
package com.some.company;
public final class MyActivity_ extends MyActivity {
// ...
}
由此可知:Activity會生成新的Activity_文件,所以AndroidManifest.xml中用到的Activity和Application都要加下劃線:xxActivity_,xxApplication_。
(四)優點
(1)簡化開發,提高效率。依賴注入layout、views、resource、service等常用操作。
(2)開放。生成的源文件可見。
(3)不影響性能。因爲不是runtime操作,都在編譯期生成新的源文件,對程序運行速度沒有影響。