Lifecycle-library-stable

Google 最近發佈了穩定Lifecyclelibrary。筆者認爲:若是你正在使用alpha或者beta版本,如下內容可能對你有用。java

Deprecated LifecycleActivity

在stable version 1.0.0 以前,LifeCycle Library 並無實現 LifecycleOwner這個接口,因此咱們不得不讓咱們項目XXXActivity繼承LifecycleActivity。筆者認爲這樣有一個毛病:該死的侵入性android

可是,在stable version 1.0.0 以後,Google可能意識到這個問題,AppCompatActivity 已經實現了LifecycleOwner 接口,這樣就能夠直接繼承原生的AppCompatActivity,而後使用它給你帶了的功能體驗app

AppCompatActivity be good for you?

我按照官方文檔建議,替換LifecycleAvtivity ,使用AppCompatActivity,代碼以下:ide

public class BaseActivity extends AppCompatActivity{
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(presenter);
    }
    
}
複製代碼

筆者提出幾點注意事項gradle

  • support:appcompat-v7 版本必定要>=26.1.0。27.0.2 對應的lifecycle version == 1.0.3
  • presenter 必須實現 LifecycleObserver 接口

Deprecated LifecycleRegistryOwner

若是你想自定義Lifecycle owner ,你應該實現 LifecycleOwner,而不是LifecycleRegistryOwnerui

Just Demo

  • build.gradle

appcompat 26.1.0 依舊使用的stable version 1.0.0, 能夠考慮手動添加最新版本。 筆者嘗試使用exclude 將appcompat中的lifecycle去掉,發現不少庫(eg:recyclerview constrait-layout fragment ...)都依賴Lifecycle, 筆者便放棄了spa

implementation 'com.android.support:appcompat-v7:26.1.0'
implementation "android.arch.lifecycle:runtime:1.0.3" 
annotationProcessor "android.arch.lifecycle:compiler:1.0.3" 
複製代碼
  • Activity
public class BaseActivity extends AppCompatActivity{
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(presenter);
    }
    
}
複製代碼
  • Observer
public class Presenter implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    public void onAny(LifecycleOwner owner, Lifecycle.Event event) {
        Log.w("@@@@ L41", "Presenter onAny -> " + "");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate() {
        Log.w("@@@@ L41", "Presenter onCreate -> " + "");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        Log.w("@@@@ L41", "Presenter onPause -> " + "");
    }
}
複製代碼
本站公眾號
   歡迎關注本站公眾號,獲取更多信息