AndroidAnnotations使用說明書—AndroidAnnotations是如何工作的?
AndroidAnnotations的工作方式很簡單,它使用標準的java注入處理工具,自動添加了一個額外的編譯步驟來產生原始碼。
源碼是什嗎?每一個增強類,比如每一個用@EActivity注入的Activity,會自動產生一個以該類類名+底線為類名的該Activity子類。
比如下面這個類:
package com.some.company;@EActivitypublic class MyActivity extends Activity { // ...}
將會產生下面這個子類,他們在同一個包下面但處在不同的檔案夾:
package com.some.company;public final class MyActivity_ extends MyActivity { // ...}
這個子類通過複寫一些方法(比如onCreate())來為你的activity增加一些行為。
上面介紹的這些就是你在AndroidManifest.xml生命Acitivty時需要為你的類名後面增加一個底線的原因:
啟動一個使用注入的Activity:
在Android中,我們通常會通過如下的方式來啟動一個activity:
startActivity(this, MyListActivity.class);
然而,如果使用AndroidAnnotations的話,真正被啟動的activity是MyListActivity_而不是MyListActivity:
startActivity(this, MyListActivity_.class);
Intent Builder(AndroidAnnotations 2.4及以上):
我們提供了一個靜態協助類來啟動編譯產生的activity:
// Starting the activityMyListActivity_.intent(context).start();// Building an intent from the activityIntent intent = MyListActivity_.intent(context).get();// You can provide flagsMyListActivity_.intent(context).flags(FLAG_ACTIVITY_CLEAR_TOP).start();// You can even provide extras defined with @Extra in the activityMyListActivity_.intent(context).myDateExtra(someDate).start();
在AndroidAnnotations 2.7及以上的版本中你可以使用另一個啟動Activity的方法startActivityForResult()了 :
MyListActivity_.intent(context).startForResult();
啟動一個使用註解的服務:
在Android中,我們通常通過如下的方式來啟動一個服務:
startService(this, MyService.class);
然而,如果使用AndroidAnnotations的話,真正被啟動的Service是MyService_而不是MyService:
startService(this, MyService_.class);
Intent Builder(AndroidAnnotations 2.7及以上版本):
我們提供了一個靜態協助類來啟動生產的Service:
// Starting the serviceMyService_.intent(context).start();// Building an intent from the activityIntent intent = MyService_.intent(context).build();// You can provide flagsMyService_.intent(context).flags(Intent.FLAG_GRANT_READ_URI_PERMISSION).start();