当前位置 : 主页 > 手机开发 > android >

如何手动暂停Android中的Activity

来源:互联网 收集:自由互联 发布时间:2021-06-11
我有两个活动,A和B.我通过以下代码从A调用了B: Intent myIntent = new Intent(this, myAcitivity.class); myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(myIntent); 并且在B上,我放置了一个按钮,通过暂
我有两个活动,A和B.我通过以下代码从A调用了B:

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

并且在B上,我放置了一个按钮,通过暂停活动B返回到活动A.我试图暂停B以使其转到背景并转到A,但它正在工作.我试过了

一解决方案:

moveTaskToBack(真);

它不是将B放在背景中,而是将A放在背景中.

有解决方案吗

Android已经为你做了这个.假设你在活动A.你开始活动B:

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

在转到myActivity之前,将调用当前活动的onPause(),其中onCreate()被调用.现在,如果你按下后退按钮,myActivity的onPause()会被调用,然后你回到活动A,在那里调用onResume().请阅读文档here和here中的活动生命周期.

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

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.

例:

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的信息.

网友评论