溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

GoogleDoc - 溫故而知新Activity生命周期方法

發(fā)布時(shí)間:2020-06-09 01:51:37 來源:網(wǎng)絡(luò) 閱讀:319 作者:屠夫章哥 欄目:移動(dòng)開發(fā)

3.創(chuàng)建Activity一般人所不知道的地方

  1)Activity里的各個(gè)生命周期的方法一般執(zhí)行什么代碼   

  》》onCreate() method shows some code that performs some fundamental setup for the activity, such as declaring the user interface (defined in an XML layout file), defining member variables, and configuring some of the UI.(填充View,定義變量。。。)

   在onCreate()方法里,對(duì)于高版本的API,應(yīng)判斷一下系統(tǒng)的的版本再?zèng)Q定是否執(zhí)行。

// Make sure we're running on Honeycomb or higher to use ActionBar APIs
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // For the main activity, make sure the app icon in the action bar
        // does not behave as a button
        ActionBar actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(false);
    }

   Caution: Using the SDK_INT to prevent older system's from executing new APIs works in this way    on Android 2.0 (API level 5) and higher only. Older versions will encounter a runtime exception.

 

 》》onPause()一般與onStop一起執(zhí)行,應(yīng)該注意它的特殊情況。

 As long as the activity is still partially visible but currently not the activity in focus, it       remains paused.(Activity可見,但是沒有獲得焦點(diǎn)就會(huì)進(jìn)行pause狀態(tài))

   As your activity enters the paused state, the system calls theonPause() method on your Activity, which allows you to stop ongoing actions that should not continue while paused (such as a video) or persist any information that should be permanently saved in case the user continues to leave your app. If the user returns to your activity from the paused state, the system resumes it and calls the onResume() method. (在onPause方法里可以停止一些操作,保留信息當(dāng)用戶離開app的時(shí)候,當(dāng)走出paused狀態(tài)時(shí),Activity會(huì)執(zhí)行onResume方法)

 

   You should usually use the onPause() callback to:


    • Stop animations or other ongoing actions that could consume CPU.(停止動(dòng)畫)

    • Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email).

    • Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.(釋放網(wǎng)絡(luò)資源)

 

Generally, you should not use onPause() to store user changes (such as personal information entered into a form) to permanent storage. The only time you should persist user changes to permanent storage withinonPause() is when you're certain users expect the changes to be auto-saved (such as when drafting an email). However, you should avoid performing CPU-intensive work during onPause(), such as writing to a database, because it can slow the visible transition to the next activity (you should instead perform heavy-load shutdown operations during onStop()).

You should keep the amount of operations done in the onPause() method relatively simple in order to allow for a speedy transition to the user's next destination if your activity is actually being stopped.

上面的文字中著重強(qiáng)調(diào)了,如果想要快速的跳轉(zhuǎn)到下一個(gè)Activity,不要將一些重量級(jí)的操作放在onPause里,而應(yīng)該放在onStop方法中。由下圖也可以領(lǐng)會(huì)這個(gè)意思:

GoogleDoc - 溫故而知新Activity生命周期方法

Note: When your activity is paused, the Activity instance is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state.

一般初始化相機(jī)的方法寫在onResume()方法中,release camera的邏輯寫在onPause中。


 》》onStop() 一般用來釋放資源,防止應(yīng)用線程被殺死。(按下Home鍵)

   When your activity receives a call to the onStop() method, it's no longer visible and should release almost all resources that aren't needed while the user is not using it. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might simply kill your app process without calling the activity's final onDestroy() callback, so it's important you use onStop() to release resources that might leak memory.

   When your activity is stopped, the Activity object is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state. The system also keeps track of the current state for each View in the layout, so if the user entered text into an EditText widget, that content is retained so you don't need to save and restore it.(Activity stop之前,對(duì)象仍然會(huì)保存在內(nèi)存當(dāng)中,沒有必要重新初始化組件了)

 Note: Even if the system destroys your activity while it's stopped, it still retains the state of the View objects (such as text in an EditText) in a Bundle (a blob of key-value pairs) and restores them if the user navigates back to the same instance of the activity (the next lesson talks more about using a Bundle to save other state data in case your activity is destroyed and recreated).(當(dāng)Activity stop的時(shí)候,即使Activity被銷毀了,仍然可以保存View的狀態(tài),當(dāng)用戶開啟新的Activity實(shí)例時(shí)會(huì)恢復(fù)它們) 

  》》onRestart() 當(dāng)Activity從stop狀態(tài)返回到前臺(tái)時(shí)執(zhí)行這個(gè)方法 

  When your activity comes back to the foreground from the stopped state, it receives a call to onRestart().The system also calls the onStart() method, which happens every time your activity becomes visible (whether being restarted or created for the first time) 

  Google重點(diǎn)強(qiáng)調(diào)了onRestart與onStart的區(qū)別,強(qiáng)烈要求onStart()與onStop配對(duì)使用,因?yàn)閛nRestart只有在從stop狀態(tài)返回的時(shí)候被調(diào)用,在Activity創(chuàng)建的時(shí)候并不會(huì)被調(diào)用。

  theonStart() method is a good place to verify that required system features are enabled:(一般在onStart()方法里進(jìn)行一些系統(tǒng)特殊是否可用的判斷)

  2)保存Activity中View的信息

  Caution: Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).  (比如在切屏的時(shí)候,Activity會(huì)銷毀,但Activity組件數(shù)據(jù)會(huì)消除怎么辦?)

  Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.(保存View的信息,要求View必須有一唯一的ID值)

  

  具體怎么保存View的狀態(tài),View的狀態(tài)又會(huì)傳到哪兒去?

To save additional data about the activity state, you must override the onSaveInstanceState() callback method. The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity is destroyed unexpectedly. If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate()methods.

  在代碼里保存信息

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first
   
    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...
}

 取出信息

public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);
   
    // Restore state members from saved instance
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}



關(guān)于activity ondestroy方法被莫明的調(diào)用的問題,手機(jī)上正常,平板會(huì)有此現(xiàn)象。

1)可能是activity在清單文件里沒有配置screenorientation="portriat"屬性,而平板一開始默認(rèn)橫屏。但是在baseactivity里又通過代碼設(shè)置了豎屏,導(dǎo)致activity被重新創(chuàng)建。



向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI