如何在Android中手动暂停活动
我有两项活动,如何在Android中手动暂停活动,android,android-intent,Android,Android Intent,我有两项活动,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(真)
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
置于背景中
有什么解决办法吗 要覆盖后退按钮的行为,您可以覆盖活动中的onBackPressed()
方法,该方法在按下后退按钮时被调用:
@Override
public void onBackPressed() {
moveTaskToBack(true); // "Hide" your current Activity
}
通过使用moveTaskToBack(true)
您的活动将被发送到后台,但不能保证它将保持“暂停”状态,如果它需要内存,Android可以将其杀死。我不知道你为什么想要这种行为,我认为最好保存活动状态并在你回来时恢复它,或者简单地用你想要的新活动启动另一个意图
或者
使用此代码onBackPressed()
Android已经在为你做这件事了。假设您在活动A中。您从以下内容开始活动B:
Intent myIntent = new Intent(this, myAcitivity.class);
startActivity(myIntent);
在转到myActivity之前,将调用当前活动的onPause(),在myActivity中调用onCreate()。现在,若您按下后退按钮,myActivity的onPause()将被调用,然后返回到活动A,其中调用onResume()。请阅读文档和中的活动生命周期
要保存活动的状态,必须重写onSaveInstanceState()回调方法:
当用户离开您的活动时,系统调用此方法,并向其传递Bundle对象,该对象将在您的活动意外销毁时保存。如果系统以后必须重新创建活动实例,它会将相同的Bundle对象传递给onrestoreinnstanceState()和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);
}
当重新创建活动时,您可以从捆绑包恢复您的状态:
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);
}
文档中有更多关于这方面的内容,请仔细阅读有关保存/恢复活动状态的内容。您可以展示这些解决方案中的任何一种吗?请尝试从活动的onPause()方法转到活动aB@PankajKumar,我提到我试过“moveTaskToBack(true);”检查我的答案或检查此链接。。
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);
}