1.向下一個活動傳遞資料。
在此就先簡單介紹一下Intent:
An intent is an abstract description of an operation to be performed. It can be used with
startActivity
to launch an Activity
, broadcastIntent
to send it to any interested BroadcastReceiver
components, and Context.startService(android.content.Intent)
or Context.bindService(android.content.Intent, android.content.ServiceConnection, int)
to communicate with a background Service
. 意思是:該Intent類是在android四大元件之間傳遞資料的信使。
Intent(Context packageContext,Class<?> cls)
Intent(Context packageContext,Class<?> cls)
Create an intent for a specific component.
Intent
putExtra(String name, String value)
Add extended data to the intent. Add extended data to the intent. The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll".
String getStringExtra(String name)Retrieve extended data from the intent.
參數: name
name
- The name of the desired item. 傳回:the value of an item that previously added with putExtra() or null if no String value was found.
例子:
@1通過Intent向下一個活動發送資料。
String data = "nihao"; Intent intent = new Intent(activity1.this,activity2.class);
intent.putExtra("send_data",data);
startActivity(intent);
@2通過intent接收來自上一個活動的資料。
Intent intent = getIntent();
String data = intent.getStringExtra("send_data");
接着介紹一下Bundle: A mapping from String values to various Parcelable types.
Bundle()
Constructs a new, empty Bundle.
Bundle()
putInt(String key, int value)
Inserts an int value into the mapping of this Bundle, replacing any existing value for the given key.
Bundle bundle = new Bundle();
bundle.putInt("operate",1);
Intent intent = new Intent(); intent.putExtra(bundle); 這樣的程式可以根據鍵值找到數值1,進而進行其他操作。 這隻是簡單的介紹一下Bundle,還有很多方法用來操作。
2.傳回資料給上一個活動。
Call this to set the result that your activity will return to its caller. 參數: - The result code to propagate back to the originating activity, often RESULT_CANCELED or RESULT_OK - The data to propagate back to the originating activity. 資料傳播回caller activity. |
Call this to set the result that your activity will return to its caller.
意思是:調用此函數将會把結果回調回caller activity.
3.開啟目前活動的onActivityResult(int requestCode, int resultCode, Intent data)方法。
Launch an activity for which you would like a result when it finished. 參數: - The intent to start. - If >= 0, this code will be returned in onActivityResult() when the activity exits. |
Launch an activity for which you would like a result when it finished. When this activity exits, your onActivityResult() method will be called with the given requestCode. Using a negative requestCode is the same as calling
startActivity(android.content.Intent)
(the activity is not launched as a sub-activity).
意思是:需要一個活動結束時傳回結果。目前活動退出,onActivityResult()方法将會被調用,如果
requestCode
< 0 時,startActivityForResult()與startActivity()效果是一樣的。