要傳遞資料給被啟動的Activity,啟用端Activity必須先使用putExtra()方法以name-value pair方式設定所要傳遞的資料。putExtra()方法第1個參數代表資料名稱,第2個參數則是為資料內容,如需要傳遞多筆資料,只要重複使用putExtra()方法即可。例如:
Intent intent = new Intent (MainActivity.this, Activity1.class);
intent.putExtra ("REQ1", "MainActivity傳遞的資料1");
intent.putExtra ("REQ2", "MainActivity傳遞來的資料2");
startActivity (intent);
被啟動的Activity,必須先使用getIntent()方法取得傳來的「Intent」物件,再透過getExtras()方法取得資料包(bundle),然後使用getString()等方法讀取指定資料。例如:
Bundle params = getIntent().getExtras();
if (params! = null) {
temp = params.getString ("REQ1") + "\n" + params.getString ("REQ2");
Toast.makeText (Activity1.this, temp, Toast.LENGTH_LONG).show();
}
如果啟用端想要由被啟動的Activity取得回傳資料,那麼啟用端必須改用startActivityForResult()方法來啟動Activity,並覆寫onActivityResult()方法來處理被啟動之Activity所回傳的資料。
startActivityForResult()方法的第二個參數為自訂的請求碼,主要是做為雙方溝通的標記,這個請求碼會在onActivityResult()方法中的第一個參數被傳回,以便onActivityResult()程式驗證回傳者身份。
//MainActivity.java
public class MainActivity extends Activity {
final int MY_ID = 100;
@Override
public void onCreate (Bundle savedInstanceState) {
Button btnobj;
super.onCreate (savedInstanceState);
setContentView (R.layout.main);
btnobj = (Button) findViewById (R.id.btnINVOKE02);
btnobj.setOnClickListener (InvokeActivity2);
}
private Button.OnClickListener InvokeActivity2 = new Button.OnClickListener () {
public void onClick (View v) {
Intent intent = new Intent (MainActivity.this, Activity2.class);
intent.putExtra ("REQ1", "MainActivity傳遞的資料1");
intent.putExtra ("REQ2", "MainActivity傳遞的資料2");
startActivityForResult (intobj, MY_ID);
}
};
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult (requestCode, resultCode, data);
if (requestCode == MY_ID){
String temp = null;
Bundle results = data.getExtras ();
if (results != null){
temp = results.getString ("ACK1") + results.getString ("ACK2");
Toast.makeText (MainActivity.this, temp, Toast.LENGTH_LONG).show();
}
}
}
}
被啟動的Activity端所要回傳的資料亦是使用putExtra ()方法設定name-value pair,之後再使用setResult ()方法回傳資料。
//Activity2.java
public class Activity2 extends Activity {
final int ACK = 200;
@Override
protected void onCreate (Bundle savedInstanceState) {
Button btnobj;
super.onCreate (savedInstanceState);
setContentView (R.layout.activity2);
btnobj = (Button) findViewById (R.id.btnRETURN);
btnobj.setOnClickListener (CloseActivity2);
String temp = null;
Bundle params = getIntent().getExtras();
if (params! = null){
temp = params.getString ("REQ1") + "\n" + params.getString ("REQ2");
Toast.makeText (Activity2.this, temp, Toast.LENGTH_LONG).show();
}
}
private Button.OnClickListener CloseActivity2 = new Button.OnClickListener() {
public void onClick (View v) {
Intent intent = new Intent ();
intent.putExtra ("ACK1", "Activity2傳回的資料1");
intent.putExtra ("ACK2", "Activity2傳回的資料2");
setResult (ACK, intent);
finish ();
}
};
}