[英]How to manually pause Activity in Android
我有兩個活動, A
和B
我A
這段代碼從A
調用了B
:
Intent myIntent = new Intent(this, myAcitivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(myIntent);
在B
,我放置一個按鈕,通過暫停活動B
返回到活動A
我試圖暫停B
以便它轉到背景並轉到A
,但它正在工作。 我試過了
一解決方案:
moveTaskToBack(true);
它不是將B
放在背景中,而是將A
放在背景中。
有解決方案嗎
要覆蓋后退按鈕,你可以重寫的行為onBackPressed()
在你的方法Activity
這是當你按下后退按鈕調用:
@Override
public void onBackPressed() {
moveTaskToBack(true); // "Hide" your current Activity
}
通過使用moveTaskToBack(true)
您的Activity被發送到后台,但無法保證它將保持“暫停”狀態,Android可以在需要內存時將其moveTaskToBack(true)
。 我不知道為什么你想要這種行為我認為最好保存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);
}
});
Android已經為你做了這個。 假設你在活動A.你開始活動B:
Intent myIntent = new Intent(this, myAcitivity.class);
startActivity(myIntent);
在轉到myActivity之前,將調用當前活動的onPause(),其中onCreate()被調用。 現在,如果你按下后退按鈕,myActivity的onPause()會被調用,然后你回到活動A,在那里調用onResume()。 請在此處和此處閱讀文檔中的活動生命周期。
要保存活動的狀態,必須覆蓋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);
}
在文檔中有更多內容,請在此處詳細了解如何保存/恢復您的活動狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.