編輯:關於 Android 開發
作為一個碼農,廢話不多說,直接上代碼。這篇記錄一下 Dagger2 的完整搭建過程,重點是 AppComponent 與 ActivityComponent 兩層的作用域劃分。
Project 級 build.gradle:

Module 級 build.gradle(關鍵是加上 apt 插件和依賴):



核心是這三行:
compile 'com.google.dagger:dagger:2.x' provided 'org.glassfish:javax.annotation:10.0-b28' apt 'com.google.dagger:dagger-compiler:2.x'
注意 dagger-compiler 必須用 apt 而不是 compile,它只在編譯期參與代碼生成,不該被打進 APK。
public class App extends Application {
private AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
}
public AppComponent getAppComponent() {
return appComponent;
}
}
記得在 AndroidManifest.xml 裡把 android:name=".App" 聲明上,否則這個 Application 不會被使用。
@Singleton
@Component(modules = { AppModule.class })
public interface AppComponent {
@ContextLife("Application")
App getApplication();
RetrofitHelper retrofitHelper(); // 提供 http 的幫助類
}
@Singleton 標在 Component 上,表示由這個 Component 提供的依賴全局唯一。注意 Dagger 的 @Singleton 作用域是「相對於 Component 而言」的,不是傳統意義的 JVM 全局單例。
@Module
public class AppModule {
private App application;
public AppModule(App application) {
this.application = application;
}
@Provides
@Singleton
@ContextLife("Application")
public App provideApplication() {
return application;
}
@Provides
@Singleton
public RetrofitHelper provideRetrofitHelper() {
return new RetrofitHelper();
}
}
@ActivityScope
@Component(dependencies = AppComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {
Activity getActivity();
void inject(LoginActivity loginActivity); // 聲明哪些類需要注入
void inject(MainActivity mainActivity);
}
dependencies = AppComponent.class 這行是重點:它讓 ActivityComponent 能夠取用 AppComponent 裡提供的依賴(比如 RetrofitHelper),形成「全局依賴在 App 層、頁面依賴在 Activity 層」的兩級結構。
@Module
public class ActivityModule {
private Activity mActivity;
public ActivityModule(Activity activity) {
this.mActivity = activity;
}
@Provides
@ActivityScope
public Activity provideActivity() {
return mActivity;
}
@Provides
@ActivityScope
public IPresenterFactory providePresenter(RetrofitHelper retrofitHelper) {
return new PresenterFactory(retrofitHelper);
}
}
自定義的 @ActivityScope 需要在 values 下新建一個 inject 包,裡面定義:
@Scope
@Retention(RUNTIME)
public @interface ActivityScope {
}
把注入流程收斂到基類,子類就不用每個都寫一遍:
public abstract class PresenterActivity extends BaseActivity {
private static final String TAG = "PresenterActivity";
protected abstract void initInject();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initInject();
}
protected ActivityComponent getActivityComponent() {
return DaggerActivityComponent.builder()
.appComponent(App.getInstance().getAppComponent())
.activityModule(getActivityModule())
.build();
}
private ActivityModule getActivityModule() {
return new ActivityModule(this);
}
}
前提條件都具備之後,點擊運行,Dagger 會自動生成 DaggerAppComponent 和 DaggerActivityComponent 兩個類(前提是沒有編譯錯誤)。然後就能用了:
public class MainActivity extends PresenterActivity {
@Inject
protected IPresenterFactory mPresenter; // 沒有 new,靠 @Inject 標簽注入
private final int BASIC_PERMISSION_REQUEST_CODE = 100;
private TextView username;
@Override
public void findView() {
username = findView(R.id.username);
username.setText(App.getInstance().getUserEntity().getName() + " hello");
}
@Override
public void init() {
if (mPresenter != null) {
Toasts.showShort("mPresenter success", context); // 注入成功會打印
}
}
@Override
public int layoutResID() {
return R.layout.activity_main;
}
@Override
protected void initInject() {
getActivityComponent().inject(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent() {
Toasts.showShort("刷新UI", context);
}
}
注入方法必須在 Component 裡聲明。忘記寫 void inject(MainActivity mainActivity),編譯能過但 @Inject 的字段全是 null。
Component 依賴項要用 builder 傳入。ActivityComponent 依賴 AppComponent,構建時必須把 App 層的 component 傳進去,否則報錯。
Dagger 生成的類找不到。九成情況是代碼有編譯錯誤,或者 apt 依賴沒配好。先看 Build 面板的錯誤,而不是急著懷疑 Dagger。
注意 Scope 的正確使用。標了 @Singleton 的依賴如果內部持有 Activity、Context 這類短生命週期對象,會導致內存洩漏。Activity 相關的依賴一律用 @ActivityScope。
Android 官方文件翻譯(十七):4.1 啟動一個 Activity
Starting an Activity(啟動一個 Activity) 本節將教你:理解生命週期回調、指定 App 的啟動 Activity、建立新的實例,以及銷毀 Ac
Android 自定義 View 實作五子棋棋盤
Android 自定義 View 實作五子棋棋盤 五子棋是很適合練習 Android 自定義 View 的小專案。整個棋盤可以封裝成一個自定義 Panel,負責繪製棋盤線
在 Android Studio 中配置 OpenCV 3.1 的完整教學
先到官網(https://opencv.org/)下載 OpenCV for Android 並解壓。由於網路因素,之前幾次下載都相當緩慢甚至中斷,後來某次意外順利完成。
交通違章查詢 App 源碼分享:用快遞 100 查詢介面自己動手做
一個小工具專案的完整拆解 這個違章查詢範例是拿快遞 100 提供的查詢介面來實作的,功能單純但流程完整,很適合當作「第三方查詢服務怎麼接進自己的 App」的參考題材。 原