Android的返回数据之前的活动(Android return data to previous

2019-07-04 06:07发布

我需要你的帮助:我想putExtra数据到以前的活动完成当前活动之前。

例如:活动开始节点B当我做完活动BI想在活动的新数据。

我该怎么办呢? 之前非常感谢

Answer 1:

Android SDK中解释这里 ,更好,所以问题的答案+例子在这里 。



Answer 2:

使用startActivityforResult打开相应的活动B..then覆盖onActivityResult(int, int, Intent)的活动为您提供..

例:

public class MyActivity extends Activity {
 ...

 static final int PICK_CONTACT_REQUEST = 0;

 protected boolean onKeyDown(int keyCode, KeyEvent event) {
     if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
         // When the user center presses, let them pick a contact.
         startActivityForResult(
             new Intent(Intent.ACTION_PICK,
             new Uri("content://contacts")),
             PICK_CONTACT_REQUEST);
        return true;
     }
     return false;
 }

 protected void onActivityResult(int requestCode, int resultCode,
         Intent data) {
     if (requestCode == PICK_CONTACT_REQUEST) {
         if (resultCode == RESULT_OK) {
             // A contact was picked.  Here we will just display it
             // to the user.
             startActivity(new Intent(Intent.ACTION_VIEW, data));
         }
     }
 }
}

检查http://developer.android.com/reference/android/app/Activity.html



Answer 3:

使用startActivityforResult开始活动B.实现覆盖onActivityResult(INT,INT,意图)的活性的方法,并在的setResult ActivityB。

例:

public class ActivityA extends Activity {

static final int REQUEST_CODE = 0;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.xyz);

        DateBtn.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    startActivityForResult(new Intent(ActivityA.this,ActivityB.class), REQUEST_CODE);
                }
            });
    }

 protected void onActivityResult(int requestCode, int resultCode,
         Intent data) {
     if (requestCode == REQUEST_CODE) {
         if (resultCode == RESULT_OK) {
             // A contact was picked.  Here we will just display it
             // to the user.
             startActivity(new Intent(Intent.ACTION_VIEW, data));
         }
     }
 }
}


public class ActivityB extends Activity {

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.xyz);

        BackBtn.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
            Intent intent = new Intent();
            intent.putExtra("DATA", "your string");
            setResult(RESULT_OK, intent);
            finish();
                }
            });
    }

}


文章来源: Android return data to previous activity