2016-03-09 499 views
3

WAY1:如何避免ActivityRecord錯誤的Activity暫停超時?

@Override 
protected void onPause() { 
    super.onPause(); 
    // do something urgent 
    doSomething(); 
} 

WAY2:

@Override 
protected void onPause() { 
    // do something urgent 
    doSomething(); 
    super.onPause(); 
} 

所不同的是的doSomething()super.onPause()呼叫序列。當我使用WAY1時,如果doSomething()的成本太高,我會得到錯誤:W/ActivityManager(4347): Activity pause timeout for ActivityRecord

如果我使用WAY2,我會避免pause timeout錯誤嗎?

我檢查了AOSP,但是我很難理解Activity的調用過程。

+0

根據http://developer.android.com/intl/es/training/basics/activity-lifecycle/pausing.html您必須始終調用超類方法 – antonio

+0

@antonio是的。我看到了。你知道原因嗎? –

+1

http://stackoverflow.com/a/9626268/1320616和http://stackoverflow.com/a/18874519/1320616將正確解釋你需要知道的一切 –

回答

3

The documentation之前清理你的變量表示,

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.

如果你看看是用於ActivityStack類「國家和活動的單一堆棧的管理。」 ,它定義

// How long we wait until giving up on the last activity to pause. This 
// is short because it directly impacts the responsiveness of starting the 
// next activity. 
static final int PAUSE_TIMEOUT = 500; 

因此,如果由onPause()執行的操作超過此超時,您將收到消息Activity pause timeout

由於此超時設置爲Activity的暫停,而onPause()只是一個回調方法,允許您在Activity暫停時執行操作,所以更改順序(WAY1或WAY2)不會影響超時(它將會在WAY1和WAY2中觸發)。爲了證明這一點,無論這些代碼打印Activity pause timeout消息:

// WAY1 
@Override 
protected void onPause() { 
    super.onPause(); 

    try { 
     Thread.sleep(501); // Don't do this!!! Only for testing purposes!!! 
    }catch (Exception e) { 
    } 
} 

// WAY2 
@Override 
protected void onPause() { 
    try { 
     Thread.sleep(501); // Don't do this!!! Only for testing purposes!!! 
    }catch (Exception e) { 
    } 

    super.onPause(); 
} 

作爲一個方面說明,我在我的評論說,the documentation說,你必須總是先調用父類的方法,但作爲@ankit AGGARWAL狀態, What is the correct order of calling superclass methods in onPause, onStop and onDestroy methods? and Why?是一個非常好的答案,解釋WAY2是否比WAY1好,爲什麼。

0

Do i avoid the pause timeout error if i use WAY2 ?

不,你不會。

你在做什麼doSomething();方法?清潔不應該花費太多時間。
如果您通過互聯網發送數據或將數據保存到數據庫?將此代碼移至Service/IntentServiceThread


呼叫super.xxx()第一或myMethod()第一?

對於我來說我寧願:

  • 調用super.xxx()FIRST在啓動方式onCreate()/onStart()/onResume()
  • 在停止方法調用super.xxx()LASTonPause()/onStop()/onDestroy()

用這種方法你保持調用堆棧, Android初始化活動(例如)中的所有內容,然後再使用它。你Android開始清潔Activity

+0

我清理'doSometing'中的相機資源。在某些設備中,Camera#release()會花費太多時間,導致ActivityRecord的'W/ActivityManager(4347):Activity暫停超時。我想知道何時開始錄製「超時」。 –

+0

@JerikcXIONG只用'Camera#release()'替代'doSomething();'並且再試一次。看看是否因爲'doSomething();'中的其他代碼 – JafarKhQ