[翻譯]用生命周期感知組件處理生命周期( Handling lifecycles with lifecycle-aware components)

前言:

這是一篇Android官方關(guān)于處理生命周期文檔的翻譯,我會(huì)貼出一段原文,然后在下面給出翻譯。圖片我保存到本地以后重新上傳了,這樣可以避免“引用圖片無(wú)法顯示”這類(lèi)問(wèn)題。翻譯的目的主要是學(xué)習(xí)這個(gè)組件的相關(guān)知識(shí)。
lifecycle-aware 我在標(biāo)題里面翻譯成“生命周期感知”了,但我覺(jué)得這個(gè)詞并不準(zhǔn)確,在正文中不翻譯,使用lifecycle-aware。
這個(gè)組件的目的是,通過(guò)將Activity或者Fragment中生命周期處理的一些代碼分離到獨(dú)立的類(lèi)中,從而使代碼簡(jiǎn)潔易于維護(hù)。用法是通過(guò)調(diào)用Activity或者Fragment的 getLifecycle().addObserver 將自定義的 LifecycleObserver 添加到 Lifecycle 中,然后就能收到生命周期的相關(guān)回調(diào),然后在Observer中處理邏輯。


原文:

Handling lifecycles with lifecycle-aware components

譯文:

用生命周期感知組件處理生命周期

原文:

Lifecycle-aware components perform actions in response to a change in the lifecycle status of another component, such as activities and fragments. These components help you produce better-organized, and often lighter-weight code, that is easier to maintain.

譯文:

lifecycle-aware 組件執(zhí)行一系列動(dòng)作來(lái)響應(yīng)其他組件生命周期狀態(tài)的變化,例如 activities 和 fragments,這些組件幫助你開(kāi)發(fā)組織得更好,更加輕量并且更容易維護(hù)的代碼。

原文:

A common pattern is to implement the actions of the dependent components in the lifecycle methods of activities and fragments. However, this pattern leads to a poor organization of the code and to the proliferation of errors. By using lifecycle-aware components, you can move the code of dependent components out of the lifecycle methods and into the components themselves.

譯文:

一個(gè)普遍的模式是,在 activities 和 fragments 的生命周期方法中實(shí)現(xiàn)所依賴(lài)組件的動(dòng)作。然而,這種模式導(dǎo)致代碼組織混亂、錯(cuò)誤擴(kuò)散。通過(guò)使用lifecycle-aware組件,你可以把所依賴(lài)組件的代碼從生命周期方法中移出來(lái),移進(jìn)它們自己的組件中。

原文:

The android.arch.lifecycle package provides classes and interfaces that let you build lifecycle-aware components—which are components that can automatically adjust their behavior based on the current lifecycle state of an activity or fragment.

譯文:

android.arch.lifecycle 包提供了類(lèi)和接口,讓你可以構(gòu)建lifecycle-aware 組件,這些組件可以根據(jù)一個(gè)Activity或者Fragment的當(dāng)前生命周期狀態(tài)自動(dòng)地調(diào)節(jié)它們的行為。

原文:

Note: To import android.arch.lifecycle into your Android project, see adding components to your project.

譯文:

注意:要在你的Android工程中引入 android.arch.lifecycle ,查閱 在你的項(xiàng)目中引入組件.

原文:

Most of the app components that are defined in the Android Framework have lifecycles attached to them. Lifecycles are managed by the operating system or the framework code running in your process. They are core to how Android works and your application must respect them. Not doing so may trigger memory leaks or even application crashes.

譯文:

Android Framework中定義的大多數(shù)app組件都附帶有生命周期。生命周期由操作系統(tǒng)或者運(yùn)行在你的進(jìn)程中的framework 代碼管理。它們是Android如何工作的核心,你的應(yīng)用必須重視它們,不這樣做可能會(huì)觸發(fā)內(nèi)存泄漏甚至應(yīng)用崩潰。

原文:

Imagine we have an activity that shows the device location on the screen. A common implementation might be like the following:

譯文:

試想我們有一個(gè)activity在屏幕上顯示設(shè)備位置,一個(gè)普遍的實(shí)現(xiàn)可能像下面那樣子:

class MyLocationListener {
    public MyLocationListener(Context context, Callback callback) {
        // ...
    }

    void start() {
        // connect to system location service
    }

    void stop() {
        // disconnect from system location service
    }
}


class MyActivity extends AppCompatActivity {
    private MyLocationListener myLocationListener;

    @Override
    public void onCreate(...) {
        myLocationListener = new MyLocationListener(this, (location) -> {
            // update UI
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        myLocationListener.start();
        // manage other components that need to respond
        // to the activity lifecycle
    }

    @Override
    public void onStop() {
        super.onStop();
        myLocationListener.stop();
        // manage other components that need to respond
        // to the activity lifecycle
    }
}

原文:

Even though this sample looks fine, in a real app, you end up having too many calls that manage the UI and other components in response to the current state of the lifecycle. Managing multiple components places a considerable amount of code in lifecycle methods, such as [onStart()](https://developer.android.com/reference/android/app/Activity.html#onStart()) and [onStop()](https://developer.android.com/reference/android/app/Activity.html#onStop()), which makes them difficult to maintain.

譯文:

盡管這個(gè)例子看起來(lái)挺好,但在一個(gè)實(shí)際的APP中,你最終會(huì)有很多響應(yīng)生命周期當(dāng)前狀態(tài)的管理UI和其他組件的調(diào)用,在一個(gè)生命周期方法中管理多個(gè)組件產(chǎn)生了一份數(shù)量相當(dāng)大的代碼。例如[onStart()](https://developer.android.com/reference/android/app/Activity.html#onStart())[onStop()](https://developer.android.com/reference/android/app/Activity.html#onStop()), 這使得它們難以維護(hù)。

原文:

Moreover, there's no guarantee that the component starts before the activity or fragment is stopped. This is especially true if we need to perform a long-running operation, such as some configuration check in [onStart()](https://developer.android.com/reference/android/app/Activity.html#onStart()). This can cause a race condition where the [onStop()](https://developer.android.com/reference/android/app/Activity.html#onStop()) method finishes before the [onStart()](https://developer.android.com/reference/android/app/Activity.html#onStart()), keeping the component alive longer than it's needed.

譯文:

另外,沒(méi)法保證組件在 activity 或者 fragment 的停止之前啟動(dòng)。假如我需要執(zhí)行一個(gè)長(zhǎng)時(shí)間運(yùn)行的操作,例如在onStart()中簽入一些配置,這可以引起一個(gè)條件競(jìng)爭(zhēng),onStop() 方法在 onStart() 方法之前結(jié)束,使得組件比需要存活的時(shí)間要長(zhǎng)。

class MyActivity extends AppCompatActivity {
    private MyLocationListener myLocationListener;

    public void onCreate(...) {
        myLocationListener = new MyLocationListener(this, location -> {
            // update UI
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Util.checkUserStatus(result -> {
            // what if this callback is invoked AFTER activity is stopped?
            if (result) {
                myLocationListener.start();
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        myLocationListener.stop();
    }
}

原文:

The android.arch.lifecycle package provides classes and interfaces that help you tackle these problems in a resilient and isolated way.

譯文:

[android.arch.lifecycle] (https://developer.android.com/reference/android/arch/lifecycle/package-summary.html) 包提供類(lèi)和接口幫助你以一個(gè)彈性和隔離的方式處理這些問(wèn)題。

原文:

Lifecycle

Lifecycle is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observe this state.

譯文:

Lifecycle 是一個(gè)類(lèi),保存了組件(例如一個(gè)activity 或者一個(gè)fragment)的生命周期狀態(tài)信息,并允許其他對(duì)象觀察這個(gè)狀態(tài)。

原文:

Lifecycle uses two main enumerations to track the lifecycle status for its associated component:

譯文:

Lifecycle 使用兩個(gè)主要的枚舉來(lái)跟蹤與之關(guān)聯(lián)組件的生命周期狀態(tài)。

原文:

Event

The lifecycle events that are dispatched from the framework and the Lifecycle class. These events map to the callback events in activities and fragments.

譯文:

事件

生命周期事件從 framework 和 Lifecycle 類(lèi)發(fā)出,這些事件映射到了 activities 和 fragments 中的回調(diào)事件。

原文:

State

The current state of the component tracked by the Lifecycle object.

譯文:

狀態(tài)

組件的當(dāng)前狀態(tài)由Lifecycle對(duì)象跟蹤。

lifecycle-states.png

原文:

Think of the states as nodes of a graph and events as the edges between these nodes.

譯文:

把圖中的節(jié)點(diǎn)想成是狀態(tài),節(jié)點(diǎn)之間的邊緣想成是事件。

原文:

A class can monitor the component's lifecycle status by adding annotations to its methods. Then you can add an observer by calling the addObserver() method of the Lifecycle class and passing an instance of your observer, as shown in the following example:

譯文:

通過(guò)給一個(gè)類(lèi)中的方法添加注解,可以監(jiān)視組件的生命周期狀態(tài)。然后你通過(guò)調(diào)用 Lifecycle 類(lèi)的 addObserver() 方法添加一個(gè) Observer,并傳遞一個(gè)你的 observer 實(shí)例,和下面的示例展示的一樣。

public class MyObserver implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void connectListener() {
        ...
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void disconnectListener() {
        ...
    }
}

myLifecycleOwner.getLifecycle().addObserver(new MyObserver());

原文:

In the example above, the myLifecycleOwner object implements the LifecycleOwner interface, which is explained in the following section.

譯文:

在上面的例子中,myLifecycleOwner 對(duì)象實(shí)現(xiàn)了 LifecycleOwner 接口,這個(gè)接口會(huì)在下面的部分講述。

原文:

LifecycleOwner

LifecycleOwner is a single method interface that denotes that the class has a Lifecycle. It has one method,getLifecycle(), which must be implemented by the class. If you're trying to manage the lifecycle of a whole application process instead, see ProcessLifecycleOwner.

譯文:

LifecycleOwner

LifecycleOwner 是一個(gè)單方法接口,表示這個(gè)類(lèi)有一個(gè)Lifecycle對(duì)象。它有一個(gè)方法 getLifecycle(), 是類(lèi)必須實(shí)現(xiàn)的。如果你嘗試管理整個(gè)應(yīng)用進(jìn)程的生命周期,查看 ProcessLifecycleOwner。

原文:

This interface abstracts the ownership of a Lifecycle from individual classes, such as [Fragment](https://developer.android.com/reference/android/support/v4/app/Fragment.html) and [AppCompatActivity](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html), and allows writing components that work with them. Any custom application class can implement the LifecycleOwner interface.

譯文:

這個(gè)接口從個(gè)別類(lèi)中抽象了 Lifecycle 的所有權(quán),例如 Fragment 和 AppCompatActivity, 并且允許編寫(xiě)和它們一起工作的組件,任何自定義的應(yīng)用類(lèi)都可以實(shí)現(xiàn) LifecycleOwner 接口。

原文:

Components that implement LifecycleObserver work seamlessly with components that implementLifecycleOwner because an owner can provide a lifecycle, which an observer can register to watch.

譯文:

實(shí)現(xiàn) LifecycleObserver 的組件和實(shí)現(xiàn) LifecycleOwner 的組件無(wú)縫地工作,因?yàn)樗姓呖梢蕴峁┮粋€(gè)生命周期,一個(gè)觀察者可以注冊(cè)觀察這個(gè)生命周期。

原文:

For the location tracking example, we can make the MyLocationListener class implement LifecycleObserver and then initialize it with the activity's Lifecycle in the [onCreate()](https://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle)) method. This allows the MyLocationListener class to be self-sufficient, meaning that the logic to react to changes in lifecycle status is declared in MyLocationListenerinstead of the activity. Having the individual components store their own logic makes the activities and fragments logic easier to manage.

譯文:

對(duì)于位置跟蹤示例,我們可以創(chuàng)建 MyLocationListener 類(lèi)實(shí)現(xiàn) LifecycleObserver,然后在 activity 的生命周期 onCreate() 中初始化它,這使得 MyLocationListener 自給自足,意味著用 MyLocationListener 中定義的生命周期狀態(tài)變化響應(yīng)邏輯替代 Activity中定義的生命周期變化。有獨(dú)立的組件保存它們自己的邏輯,使得 activities 和 fragments 邏輯容易管理。

class MyActivity extends AppCompatActivity {
    private MyLocationListener myLocationListener;

    public void onCreate(...) {
        myLocationListener = new MyLocationListener(this, getLifecycle(), location -> {
            // update UI
        });
        Util.checkUserStatus(result -> {
            if (result) {
                myLocationListener.enable();
            }
        });
  }
}

原文:

A common use case is to avoid invoking certain callbacks if the Lifecycle isn't in a good state right now. For example, if the callback runs a fragment transaction after the activity state is saved, it would trigger a crash, so we would never want to invoke that callback.

譯文:

一個(gè)常見(jiàn)的使用場(chǎng)景是避免調(diào)用特定的回調(diào),如果 Lifecycle 現(xiàn)在還不是一個(gè)合適的狀態(tài)。例如,activity state 保存以后,回調(diào)運(yùn)行一個(gè) fragment 事務(wù)的會(huì)觸發(fā)一個(gè)崩潰,因此我們絕不想調(diào)用這個(gè)回調(diào)。

原文:

To make this use case easy, the Lifecycle class allows other objects to query the current state.

譯文:

為了使這個(gè)場(chǎng)景容易使用,Lifecycle 類(lèi)允許其他對(duì)象查詢(xún)當(dāng)前的狀態(tài)。

class MyLocationListener implements LifecycleObserver {
    private boolean enabled = false;
    public MyLocationListener(Context context, Lifecycle lifecycle, Callback callback) {
       ...
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void start() {
        if (enabled) {
           // connect
        }
    }

    public void enable() {
        enabled = true;
        if (lifecycle.getCurrentState().isAtLeast(STARTED)) {
            // connect if not connected
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void stop() {
        // disconnect if connected
    }
}

原文:

With this implementation, our LocationListener class is completely lifecycle-aware. If we need to use our LocationListener from another activity or fragment, we just need to initialize it. All of the setup and teardown operations are managed by the class itself.

譯文:

通過(guò)這個(gè)實(shí)現(xiàn),我們的 LocationListener 類(lèi)是完全生命周期感知的,如果我們需要在另外一個(gè) activity 或者 fragment 使用我們的 LocationListener, 我們只需要初始化它,所有的安裝和拆除操作由類(lèi)自己管理。

原文:

If a library provides classes that need to work with the Android lifecycle, we recommend that you use lifecycle-aware components. Your library clients can easily integrate those components without manual lifecycle management on the client side.

譯文:

如果一個(gè)庫(kù)提供的類(lèi)需要和 Android 的生命周期一起工作,我們推薦你使用 lifecycle-aware 組件。你的庫(kù)的客戶(hù)可以很容易地集成那些組件,并且不需要在客戶(hù)端做手工的生命周期管理。

原文:

Implementing a custom LifecycleOwner

Fragments and Activities in Support Library 26.1.0 and later already implement the LifecycleOwner interface.

譯文:

實(shí)現(xiàn)一個(gè)自定義的 LifecycleOwner

在 Support Library 26.1.0 和以后的庫(kù)中,F(xiàn)ragments 和 Activities 已經(jīng)實(shí)現(xiàn)了 LifecycleOwner 接口。

原文:

If you have a custom class that you would like to make a LifecycleOwner, you can use the LifecycleRegistry class, but you need to forward events into that class, as shown in the following code example:

譯文:

如果你想把一個(gè)自定義的的類(lèi)做成一個(gè) LifecycleOwner, 你可以使用 LifecycleRegistry 類(lèi),但是需要你向那個(gè)類(lèi)分發(fā)事件,像下面的代碼示例展示的:

public class MyActivity extends Activity implements LifecycleOwner {
    private LifecycleRegistry mLifecycleRegistry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mLifecycleRegistry = new LifecycleRegistry(this);
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
    }

    @Override
    public void onStart() {
        super.onStart();
        mLifecycleRegistry.markState(Lifecycle.State.STARTED);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

原文:

Best practices for lifecycle-aware components

Keep your UI controllers (activities and fragments) as lean as possible. They should not try to acquire their own data; instead, use a ViewModel to do that, and observe a LiveData object to reflect the changes back to the views.

譯文:

lifecycle-aware 組件最佳實(shí)踐

保持你的 UI 控制(activities and fragments)盡可能簡(jiǎn)潔。他們不應(yīng)該嘗試獲取它們自己的數(shù)據(jù),可替代的,使用一個(gè) ViewModel 做這個(gè),并且觀察一個(gè) LiveData 對(duì)象把變化反映到視圖。

原文:

Try to write data-driven UIs where your UI controller’s responsibility is to update the views as data changes, or notify user actions back to the ViewModel.

譯文:

嘗試編寫(xiě)數(shù)據(jù)驅(qū)動(dòng)的UI,你的UI控制器的職責(zé)是在數(shù)據(jù)變化時(shí)更新視圖,或者把用戶(hù)的動(dòng)作回饋給 ViewModel。

原文:

Put your data logic in your ViewModel class. ViewModel should serve as the connector between your UI controller and the rest of your app. Be careful though, it isn't ViewModel's responsibility to fetch data (for example, from a network). Instead, ViewModel should call the appropriate component to fetch the data, then provide the result back to the UI controller.

譯文:

把你的數(shù)據(jù)邏輯放在 ViewModel 類(lèi)中,ViewModel 像連接器一樣服務(wù)在你的UI控制器和應(yīng)用的其余部分。但是要小心,獲取數(shù)據(jù)(例如,從網(wǎng)絡(luò))不是 ViewModel 的職責(zé),而是,ViewModel 應(yīng)該調(diào)用合適的組件來(lái)獲取數(shù)據(jù),然后給UI控制器提供結(jié)果。

原文:

Use Data Binding to maintain a clean interface between your views and the UI controller. This allows you to make your views more declarative and minimize the update code you need to write in your activities and fragments. If you prefer to do this in the Java programming language, use a library like Butter Knife to avoid boilerplate code and have a better abstraction.

譯文:

使用 Data Binding 在你的視圖和UI控制器之間維護(hù)一個(gè)整潔的接口,這會(huì)讓你的視圖更有說(shuō)明性,并且減少你在 activities和 fragments 中需要編寫(xiě)的更新代碼。如果你喜歡用java編程語(yǔ)言做這個(gè),使用像 Butter Knife 這樣的庫(kù)來(lái)避免樣板化的代碼,并且有一個(gè)更好的抽象。

原文:

If your UI is complex, consider creating a presenter class to handle UI modifications. This might be a laborious task, but it can make your UI components easier to test.

譯文:

如果你的UI復(fù)雜,考慮創(chuàng)建一個(gè) presenter 類(lèi)來(lái)處理 UI更新,這可能是一項(xiàng)體力勞動(dòng),但它會(huì)使得你的UI組件容易測(cè)試。

原文:

Avoid referencing a [View](https://developer.android.com/reference/android/view/View.html) or [Activity](https://developer.android.com/reference/android/app/Activity.html) context in your ViewModel. If the ViewModel outlives the activity (in case of configuration changes), your activity leaks and isn't properly disposed by the garbage collector.

譯文:

避免在你的ViewModel中引用一個(gè) View 或者 Activity context。如果 ViewModel 比 activity (例如配置改變) 存活時(shí)間長(zhǎng),你的 activity 會(huì)泄漏從而不能被垃圾回收合適地處理。

原文:

Use cases for lifecycle-aware components

Lifecycle-aware components can make it much easier for you to manage lifecycles in a variety of cases. A few examples are:

譯文:

lifecycle-aware 組件的使用場(chǎng)景

lifecycle-aware 組件可以使你管理各種各樣的生命周期更加簡(jiǎn)單,幾個(gè)例子:

原文:

Switching between coarse and fine-grained location updates. Use lifecycle-aware components to enable fine-grained location updates while your location app is visible and switch to coarse-grained updates when the app is in the background. LiveData, a lifecycle-aware component, allows your app to automatically update the UI when your user changes locations.

譯文:

在大致的和精準(zhǔn)的位置更新之間切換,使用 lifecycle-aware 組件,當(dāng)你的位置應(yīng)用可見(jiàn)時(shí),啟用精準(zhǔn)的位置更新,當(dāng)應(yīng)用在后臺(tái)時(shí),使用大致的位置更新。LiveData 一個(gè) lifecycle-aware 組件,可以在用戶(hù)改變位置時(shí),讓你的應(yīng)用 自動(dòng)更新UI。

原文:

Stopping and starting video buffering. Use lifecycle-aware components to start video buffering as soon as possible, but defer playback until app is fully started. You can also use lifecycle-aware components to terminate buffering when your app is destroyed.

譯文:

停止和開(kāi)始視頻緩沖,使用 lifecycle-aware 組件盡可能快地開(kāi)始視頻緩沖,但是推遲播放到應(yīng)用完全啟動(dòng)。你還可以用 lifecycle-aware 組件在應(yīng)用銷(xiāo)毀時(shí)結(jié)束緩沖。

原文:

Starting and stopping network connectivity. Use lifecycle-aware components to enable live updating (streaming) of network data while an app is in the foreground and also to automatically pause when the app goes into the background.

譯文:

開(kāi)始和停止網(wǎng)絡(luò)連接。當(dāng)應(yīng)用在前臺(tái)時(shí)使用 lifecycle-aware 組件來(lái)啟用網(wǎng)絡(luò)數(shù)據(jù)更新,當(dāng)應(yīng)用進(jìn)入后臺(tái)時(shí)自動(dòng)暫停。

原文:

Pausing and resuming animated drawables. Use lifecycle-aware components to handle pausing animated drawables when while app is in the background and resume drawables after the app is in the foreground.

譯文:

暫停和恢復(fù)動(dòng)畫(huà),當(dāng)應(yīng)用在后臺(tái)時(shí)使用 lifecycle-aware 組件處理動(dòng)畫(huà)暫停,并在應(yīng)用到前臺(tái)以后恢復(fù)。

原文:

Handling on stop events

When a Lifecycle belongs to an [AppCompatActivity](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html) or [Fragment](https://developer.android.com/reference/android/support/v4/app/Fragment.html), the Lifecycle's state changes to CREATEDand the ON_STOP event is dispatched when the [AppCompatActivity](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html) or [Fragment](https://developer.android.com/reference/android/support/v4/app/Fragment.html)'s [onSaveInstanceState()](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#onSaveInstanceState(android.os.Bundle)) is called.

譯文:

處理on stop事件

當(dāng)一個(gè) Lifecycle 屬于一個(gè) AppCompatActivity 或者 Fragment 的時(shí)候,Lifecycle 的狀態(tài)變成了 CREATED ,當(dāng) AppCompatActivity 或 Fragment 的 onSaveInstanceState() 被調(diào)用時(shí),ON_STOP 事件被分發(fā)。

原文:

When a [Fragment](https://developer.android.com/reference/android/support/v4/app/Fragment.html) or [AppCompatActivity](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html)'s state is saved via [onSaveInstanceState()](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#onSaveInstanceState(android.os.Bundle)), it's UI is considered immutable until ON_START is called. Trying to modify the UI after the state is saved is likely to cause inconsistencies in the navigation state of your application which is why [FragmentManager](https://developer.android.com/reference/android/support/v4/app/FragmentManager.html) throws an exception if the app runs a[FragmentTransaction](https://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html) after state is saved. See [commit()](https://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html#commit()) for details.

譯文:

當(dāng)一個(gè) Fragment 或者 AppCompatActivity 的狀態(tài)通過(guò) onSaveInstanceState() 保存以后,它的UI被認(rèn)為是不可用修改的,直到 ON_START 被調(diào)用,在狀態(tài)被保存以后嘗試修改UI可能會(huì)引起應(yīng)用導(dǎo)航狀態(tài)的不一致,這是為什么應(yīng)用在狀態(tài)保存以后運(yùn)行 FragmentTransaction時(shí),F(xiàn)ragmentManager 拋出一個(gè)異常的原因。查看[commit()](https://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html#commit())了解更多。

原文:

LiveData prevents this edge case out of the box by refraining from calling its observer if the observer's associated Lifecycle isn't at least STARTED. Behind the scenes, it calls isAtLeast() before deciding to invoke its observer.

譯文:

LiveData 阻止這種邊緣情形的發(fā)生--通過(guò)阻止對(duì)它的觀察者的調(diào)用, 如果觀察者所關(guān)聯(lián)的 Lifecycle 至少不在 STARTED。在這種情形下,它在決定調(diào)用它的觀察者之前,先調(diào)用 isAtLeast() 。

原文:

Unfortunately, [AppCompatActivity](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html)'s [onStop()](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#onStop()) method is called after [onSaveInstanceState()](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#onSaveInstanceState(android.os.Bundle)), which leaves a gap where UI state changes are not allowed but the Lifecycle has not yet been moved to the CREATED state.

譯文:

不幸的是,AppCompatActivity 的 onStop() 方法在 onSaveInstanceState() 之后調(diào)用,這在不允許 UI 狀態(tài)改變但 Lifecycle 也沒(méi)有移動(dòng)到 CREATED 之間留下了缺口。

原文:

To prevent this issue, the Lifecycle class in version beta2 and lower mark the state as CREATED without dispatching the event so that any code that checks the current state gets the real value even though the event isn't dispatched until [onStop()](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#onStop()) is called by the system.

譯文:

為了防止這個(gè)問(wèn)題,Lifecycle 類(lèi)在 beta2 和更低版本把狀態(tài)標(biāo)記成 CREATED, 但沒(méi)有分發(fā)事件,因此任何檢查當(dāng)前狀態(tài)的代碼都會(huì)得到真正的值,盡管直到系統(tǒng)調(diào)用了onStop()都沒(méi)有分發(fā)事件。

原文:

Unfortunately, this solution has two major problems:

譯文:

不幸的是,這個(gè)方案有兩個(gè)主要問(wèn)題:

原文:

  • On API level 23 and lower, the Android system actually saves the state of an activity even if it is partially covered by another activity. In other words, the Android system calls [onSaveInstanceState()](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#onSaveInstanceState(android.os.Bundle)) but it doesn't necessarily call [onStop()](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#onStop()). This creates a potentially long interval where the observer still thinks that the lifecycle is active even though its UI state can't be modified.

譯文:

在 API 23 及更低,Android 系統(tǒng)實(shí)際會(huì)在一個(gè) Activity 被其他 Activity 部分覆蓋時(shí)保存它的狀態(tài),換句話說(shuō),Android 系統(tǒng)調(diào)用 onSaveInstanceState() 但它未必會(huì)調(diào) onStop(),這制造了一個(gè)潛在的長(zhǎng)時(shí)間間隔,在這段時(shí)間里觀察者一直認(rèn)為生命周期是活動(dòng)的但UI的狀態(tài)不能被修改。

原文:

  • Any class that wants to expose a similar behavior to the LiveData class has to implement the workaround provided by Lifecycle version beta 2 and lower.

譯文:

任何類(lèi)想暴露一個(gè)類(lèi)似的行為給 LiveData 類(lèi),就不得不實(shí)現(xiàn) Lifecycle beta 2 和更低版本提供的變通方案。

原文:

Note: To make this flow simpler and provide better compatibility with older versions, starting at version 1.0.0-rc1, Lifecycle objects are marked as CREATED and ON_STOP is dispatched when [onSaveInstanceState()](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#onSaveInstanceState(android.os.Bundle)) is called without waiting for a call to the [onStop()](https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#onStop()) method. This is unlikely to impact your code but it is something you need to be aware of as it doesn't match the call order in the [Activity](https://developer.android.com/reference/android/app/Activity.html) class in API level 26 and lower.

譯文:

注意: 為了使得這個(gè)流程簡(jiǎn)單,并且提供更好的老版本兼容,從 1.0.0-rc1 版本開(kāi)始。Lifecycle 對(duì)象被標(biāo)記成 CREATED ,并且當(dāng) onSaveInstanceState() 調(diào)用時(shí)不等待 onStop() 方法的調(diào)用就分發(fā) ON_STOP。這未必影響你的代碼,但是你需要注意的事情,因?yàn)樗黄ヅ?API 26 以及更低版本中 Activity 類(lèi)的調(diào)用順序。

原文:

Additional resources

Lifecyle-aware components are part of Android Jetpack. See them in use in the Sunflower demo app.

譯文:

附加資源:

Lifecyle-aware 組件是 Android Jetpack 的一部分,在 Sunflower 示例應(yīng)用中查看。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,675評(píng)論 25 709
  • 劉溪,遠(yuǎn)大住工國(guó)際;國(guó)學(xué)踐行23期學(xué)員,24期奉獻(xiàn)者,六項(xiàng)精進(jìn)299期同修【知~學(xué)習(xí)》 【日精進(jìn)第29天】 《六項(xiàng)...
    西西_3e45閱讀 157評(píng)論 0 0
  • 很倒霉的你,如果總是被拒絕怎么辦。 恭喜你,又收獲一次拒絕??偸潜痪芙^難道害怕再被拒絕一次嗎。據(jù)我所知,在所有星座...
    青木川_閱讀 301評(píng)論 0 0
  • 看此章節(jié),聯(lián)想到工作和生活,感覺(jué)很多時(shí)候會(huì)忽略了細(xì)節(jié),并由此帶來(lái)不良后果。比如我們的內(nèi)勤工作,就是需要仔細(xì)...
    塵埃wyzh閱讀 356評(píng)論 0 0
  • 距今學(xué)習(xí)前端已經(jīng)有一個(gè)多月了,大概六月上旬開(kāi)始看視頻教程和做練習(xí),直到現(xiàn)在剛做完JS進(jìn)階(其實(shí)是入門(mén))的最后一道習(xí)...
    Portuense閱讀 429評(píng)論 0 1

友情鏈接更多精彩內(nèi)容