从未从当前活动开始的活动中获取额外价值

时间:2016-10-14 19:16:49

标签: android

我知道如何使用startActivityForResult从另一个活动中获取结果,但问题是我有3个活动A,B和C.主要活动是A,所有活动的后退按钮都应该返回。< / p>

现在我们从活动A打开活动B,然后从活动B打开活动C.当在活动C上按下后退按钮时,如何将结果返回到活动A?

活动A:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            int result=data.getIntExtra("result", 0);
            SetNotification(result);
        }
    }
}

活动C:

 //This works for activity B which is started directly from activity A
@Override
public void onBackPressed() {
    Intent returnIntent = new Intent();
    returnIntent.putExtra("result", unreadCount);
    setResult(Activity.RESULT_OK,returnIntent);
    finish();
}

4 个答案:

答案 0 :(得分:1)

“当在活动C上按下后退按钮时,如何将结果返回到活动A?”

不要回去。前进,年轻的蚱蜢:P

Intent intent = new Intent(this, activityClass);

// FLAG_ACTIVITY_NEW_TASK : If set, this activity will become the start of a new task on this history stack.
// FLAG_ACTIVITY_CLEAR_TOP: If set, and the activity being launched is already running in the current task, 
// then instead of launching a new instance of that activity, all of the other activities on 
// top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

intent.putExtra("result", unreadCount);

startActivity(intent);

答案 1 :(得分:0)

我会这样做:

@Override
public void onBackPressed() {
   Intent returnIntent = new Intent(C.this, A.class);
   returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
   returnIntent.putExtra("result", unreadCount);
   startActivity(intent);
}

然后你可以在A&#39; onCreate()中获取你的额外内容。

希望它有所帮助。

答案 2 :(得分:0)

也许您可以使用活动B中的onActivityResult()将调用重定向到活动A.这样的事情:

// Activity B
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK){
                // Get data from activity C
                int result = data.getIntExtra("result", 0);

                // Create intent with data from activity C
                Intent returnIntent = new Intent();
                returnIntent.putExtra("result", result);

                // Set the response
                setResult(Activity.RESULT_OK,returnIntent);
                finish();
            }
        }
    }

答案 3 :(得分:0)

当按下ActivityC后调用ActivityB的onActivityResult时,ActivityB可以将此结果传递给ActivityA。所以ActivityB可以做到如下:

@覆盖 protected void onActivityResult(int requestCode,int resultCode,Intent data){

if (requestCode == 1) {
    if(resultCode == Activity.RESULT_OK){
        int result=data.getIntExtra("result", 0);

       Intent returnIntent = new Intent();
       returnIntent.putExtra("result", result);
       setResult(Activity.RESULT_OK,returnIntent);
       finish();
    }
}

}