与堆栈中的活动通信

时间:2017-05-19 15:32:15

标签: android

让我们考虑以下情况:

Activity A打开Activity B。现在,A位于activity stackB从互联网下载任何数据,并根据这些数据得出结论,当用户返回A时(按下后)A应刷新其内容。怎么说:B: Hey A in stack, please remember that you should refresh your content。我看到我可以在App实例中设置一些标志,但是,它似乎很奇怪。

2 个答案:

答案 0 :(得分:1)

考虑在ActivityA中使用 startActivityForResult 来调用ActivityB,然后在ActivityB中覆盖onBackPressed()方法,并根据下载的数据调用setResult()。最后回到您的ActivityA覆盖onActivityResult(int requestCode, int resultCode, Intent data)

使用以下示例作为指南:

<强> ActivityA.java

public class ActivityA extends AppCompatActivity {

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent(this, ActivityB.class);
    startActivityForResult(intent, 1234);
}

@Override
protected void onActivityResult(final int requestCode, final int resultCode, Intent intent) {
    if (1234 == requestCode) {
        if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "Do action 1", Toast.LENGTH_SHORT).show();
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(this, "Do action 2", Toast.LENGTH_SHORT).show();
        }
    }
}

}

<强> ActivityB.java

public class ActivityB extends AppCompatActivity {

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public void onBackPressed() {
    final Intent intent = new Intent();
    if (true) {  //Replace this condition by yours based on downloaded data
        setResult(Activity.RESULT_OK, intent);
    } else {
        setResult(Activity.RESULT_CANCELED, intent);
    }
    super.onBackPressed();
}
}

答案 1 :(得分:0)

不那样。始终在A活动的onResume()方法中更新活动A内容。