// MainActivity. javaIntent intent = new Intent (); Bundle bundle = new Bundle (); bundle. putInt ("data1", 10); bundle. putString ("data2", "data"); // switch from the current MainActivity to Activity2intent. setClass (MainActivity. this, Activity2.class); intent. putExtras (bundle); // start to execute switching this. startActivity (intent );
// Activity2.javaIntent intent = getIntent (); // obtain the value of the corresponding key in the Extra of this Intent object. int data1 = intent. getExtras (). getInt ("data1"); String data2 = intent. getExtras (). getString ("data2 ");
1. startActivity method jump
The above code generates an Intent object and a Bundle object.
The Intent object is the parameter used by the startActivity method during switchover.
The Bundle object is the key-value pair data that is stored and sent to the target Activity2 object. This object can be left unspecified.
In Activity2, use the getIntent method to obtain the passed Intent object and obtain the key-value pair data.
2. startActivityForResult method jump
The previous startActivity method can pass data from MainActivity to Activity2.
If you want to obtain data after Activity2 is executed, MainActivity is returned.
The startActivityForResult method is used.
The most common requirement for this application is to determine the pop-up window and Other interfaces.
//MainActivity.java
Intent intent = new Intent (); intent. setClass (MainActivity. this, Activity2.class );
Bundle bundle = new Bundle ();
Bundle. putInt ("data1", 10 );
Bundle. putString ("data2", "data ");
Intent. putExtras (bundle );
StartActivityForResult (intent, 0 );
Here there is only one method that changes nothing elseActivity2 does not need to change the received key-value pairs.
Only call setResult at the end
// Activity2.javaIntent intent = new Intent (); intent. putExtra ("res1", 1); intent. putExtra ("res2", "res"); // The Request Code can set setResult (RESULT_ OK, intent); // close Activity2finish ();
Override onActivityResult in MainActivity//MainActivity.javaprotected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stubsuper.onActivityResult(requestCode, resultCode, data);switch(resultCode){case RESULT_OK:String str1 = data.getStringExtra("res1");String str2 = data.getStringExtra("res2");finish();break;default:break;}//switch}//onActivityResult