2016-03-09 1967 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