iT邦幫忙

2022 iThome 鐵人賽

DAY 16
0

Lifecycle是一個生命週期感知型組件,一般用來響應Activity/Fragment、Service等生命週期狀態的變化。

Jectpack 是一個由多個庫組成的套件,可幫助開發者遵循最佳做法、減少樣板程式碼並編寫可在各種Android版本和裝置中都能維持一致運作方式的程式碼,讓開發人員能專心處理重要的程式碼。

Lifecycle 使用兩種主要枚舉追蹤其關聯組件的生命週期狀態

  • 事件(Events)、狀態(States)

環境配置

  • build.gradle(Module)
dependencies {
    ...
    
    def lifecycle_version = "2.5.1"
    def arch_version = "2.1.0"

    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
    // Lifecycles only (without ViewModel or LiveData)
    implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"

    // Saved state module for ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"

    // Annotation processor
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
    // alternately - if using Java8, use the following instead of lifecycle-compiler
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

    // optional - helpers for implementing LifecycleOwner in a Service
    implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"

    // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process
    implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"

    // optional - ReactiveStreams support for LiveData
    implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version"

    // optional - Test helpers for LiveData
    testImplementation "androidx.arch.core:core-testing:$arch_version"

    // optional - Test helpers for Lifecycle runtime
    testImplementation "androidx.lifecycle:lifecycle-runtime-testing:$lifecycle_version"
}

簡單使用之範例

- 沒有使用Lifecycle

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "ian";
    private ActivityMainBinding binding;
    private long elapsedTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "計時器'開始'計時 - ON_RESUME");
        binding.chronometer.setBase(SystemClock.elapsedRealtime() - elapsedTime); // 設置初始時間
        binding.chronometer.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "計時器'暫停'計時 - ON_PAUSE");
        elapsedTime = SystemClock.elapsedRealtime() - binding.chronometer.getBase();
        binding.chronometer.stop();
    }
}

- 使用了Lifecycle

  • 觀察者 - 將計時器實踐(implements)LifecycleEventObserver接口
    public class MyChronometer extends Chronometer implements LifecycleEventObserver {
        private static final String TAG = "ian";
        private long elapsedTime;
    
        public MyChronometer(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
            switch (event) {
                case ON_PAUSE:
                    Log.d(TAG, "計時器'暫停'計時 - ON_PAUSE");
                    elapsedTime = SystemClock.elapsedRealtime() - getBase();
                    stop();
                    break;
                case ON_RESUME:
                    Log.d(TAG, "計時器'開始'計時 - ON_RESUME");
                    setBase(SystemClock.elapsedRealtime() - elapsedTime);
                    start();
                    break;
            }
        }
    }
    
  • 被觀察者 - Activity 通過addObserver註冊觀察者
    public class MainActivity extends AppCompatActivity {
        private static final String TAG = "ian";
        private ActivityMainBinding binding;
        private long elapsedTime;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            binding = ActivityMainBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());
            // 通過addObserver註冊觀察者
            getLifecycle().addObserver(binding.chronometer);
        }
    }
    

上一篇
Day15 - Android - MVC、MVP、MVVM 設計架構
下一篇
Day17 - ViewModel | Android Jetpack
系列文
Android 開發 30天 初學之路筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言