[英]Return to MainActivity with added data from another Activity
我知道如何將數據從活動發送到Next Activity
:[ Intent.putExtra(key, value);
]。
我也知道如何從一個活動返回到上一個活動,並包括數據:[ 請參見stackoverflow答案 ]。
但是,我想知道的是如何返回家庭作業並包含數據。 舉個例子:
在第4步中,我想做一些與onResume(或它返回的其他方法)中的正常操作不同的事情,因此,我包含的數據是帶有鍵的布爾值(最好使用intent.putExtra("myKey", true);
(或如果失敗,則返回false)。 然后在onResume中執行以下操作:
@Override
protected void onResume(){
super.onResume();
if(intent.getExtras() != null && intent.getAction().toString().equals("myKey")){
if(intent.getExtras().getBoolean("myKey")){
// do something else (step 4) on success
}
else{
// do something else (step 4) on fail
}
}
else{
// Do regular stuff I normally do in the onResume()
}
}
好的,我想我已經解決了我的問題。
我的HomeActivity已經是一個BroadcastReceiver,所以我只是使用廣播將意圖從最后一個Activity發送到我的HomeActivity。
將對此進行測試以查看其是否有效。
雖然我有點懷疑當我參加另一項活動時會否。
(我的HomeActivity已經是我必須發送的一些Http請求的廣播接收器,並且需要它的結果,它們當然是AsyncTasks。)
好的,當我不在MainActvity中時,這將不起作用。 因此歡迎更多建議。
好的,我找到了一個解決方案(也要感謝shimi_tab的回答和Budius對onNewIntent的 評論 ):
在我想返回的活動C中:
Intent home = new Intent(this, A.class);
home.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
home.putExtra("myKey", true);
startActivity(home);
在我的活動A中:
// This allows us to use getIntent to get the latest intent, instead of the first Intent used in the onCreate
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
@Override
protected void onResume(){
super.onResume();
if(getIntent().getExtras() != null && getIntent().getExtras().getBoolean("myKey")){
// Do something else after returning from C
}
else{
// Do regular things on a normal onResume (like back from B or Settings)
}
}
注意(與原始問題googleApiClient.onConnect();
):在我的情況下,我在活動A中使用了Google Services,其中我有googleApiClient.onConnect();
在onStart()
方法中。 因此,我還必須將以下內容添加到onConnected()
方法中:
@Override
public void onConnected(Bundle b){
Bundle extras = getIntent().getExtras();
if(extras == null || (extras != null && !extras.getBoolean("myKey"))){
// Do regular stuff
}
else{
// Do something else after we returned from C
}
}
要將數據放回調用活動,您將使用以下方法:
public final void setResult (int resultCode, Intent data)
根據這種意圖,您可以隨意填寫所需的所有數據。 活動結果方法如下:
protected void onActivityResult (int requestCode, int resultCode, Intent data)
因此,您輸入的結果就是相同的數據。
您應減少活動“ A”狀態。 使用標志FLAG_ACTIVITY_CLEAR_TOP的新意圖再次調用活動“ A”。
Intent intent = new Intent(this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
以及您想要的所有數據。
您不應該在ActivityResult上進行中繼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.