如何手动暂停Android中的Activity

时间:2013-11-25 06:21:12

标签: android android-intent

我有两项活动AB。我通过以下代码致电B A

 Intent myIntent = new Intent(this, myAcitivity.class);        
 myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 startActivity(myIntent);

B上,我通过暂停活动A放置了一个按钮以返回到活动B。我试图暂停B以便它转到后台并转到A,但它正在运行。我试过了

一个解决方案:

moveTaskToBack(true);

不是将B放在后台,而是将A放在后台。

任何解决方案?

2 个答案:

答案 0 :(得分:5)

要覆盖后退按钮的行为,您可以覆盖按下后退按钮时调用的onBackPressed()中的Activity方法:

@Override
public void onBackPressed() {
   moveTaskToBack(true);  // "Hide" your current Activity
}

通过使用moveTaskToBack(true)您的活动被发送到后台,但无法保证它将保持“暂停”状态,Android可以在需要内存时将其终止。我不知道为什么你想要这种行为我认为最好保存Activity状态并在你回来时恢复它,或者简单地用你想要带来的新Activity启动另一个Intent。

或者,

使用此代码onBackPressed()

boolean mIsPaused = false;

final Thread workerThread = new Thread(new Runnable() {
  @Override
  public void run() {
  doA();
  checkPause();
  doB();
  checkPause();
  ...
 }
 }
});

private void checkPause() {
while(isPaused()) {
  // you could also use the notify/wait pattern but that is probably needless     complexity for this use case.
  Thread.sleep(50);
 }
}

private synchronized boolean isPaused() {
return mIsPaused;
}

 private synchronized void setPaused(boolean isPaused) {
 mIsPaused = isPaused;
 }


 pauseButton.setOnLongClickListener(new View.OnLongClickListener() {
 @Override
 public boolean onLongClick(View v) {
  // disable any UI elements that need it
  setIsPaused(true);
 }
});

 unPauseButton.setOnLongClickListener(new View.OnLongClickListener() {
  @Override
 public boolean onLongClick(View v) {
  // re-enable any UI elements that need it
  setIsPaused(false);
 }
});

答案 1 :(得分:2)

Android已经在为你做这个了。假设您正在参加活动A.您可以通过以下方式开始活动B.

Intent myIntent = new Intent(this, myAcitivity.class);
startActivity(myIntent);
在转到myActivity之前,将调用当前活动的

onPause(),其中onCreate()被调用。现在,如果你按下后退按钮,myActivity的onPause()会被调用,然后你回到活动A,在那里调用onResume()。请在文档herehere中了解活动生命周期。

要保存活动的状态,必须覆盖onSaveInstanceState()回调方法:

  

系统在用户离开您的活动时调用此方法,并向其传递Bundle对象,该对象将在您的活动意外销毁时保存。如果系统必须稍后重新创建活动实例,它会将相同的Bundle对象传递给onRestoreInstanceState()和onCreate()方法。

示例:

static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

当您重新创建活动时,您可以从Bundle中恢复您的状态:

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);
}

在文档中有更多内容,请详细了解如何保存/恢复您的活动状态here