【Android基礎】利用Intent在Activity之間傳遞數據
前言:
上一篇文章給大家聊了Intent的使用方法。怎樣用Intent啟動Activity和隱式Intent。這一篇文章給大家聊聊怎樣利用Intent在Activity之間進行溝通。從一個Activity獲取返回結果:
啟動一個Activity不不過startActivity(Intent intent)一種方法。你也能夠通過startActivityForResult()啟動一個Activity而且在它退出的時候收到一個返回結果。
比方。你能夠調用系統相機在你的應用中,拍了一張照片,然後返回到你的Activity,這個時候就能夠通過這樣的方法把照片作為結果返回給你的Activity。
再比方。你能夠通過這樣的方法啟動系統聯系人應用,然後獲取一個人的具體聯系方式。
註意:在調用startActivityForResult()時你可以利用顯示Intent或者隱式Intent。可是在你可以利用顯式Intent的時候盡量利用顯式Intent。這樣可以保證返回的結果是你期待的正確結果。
啟動一個Activity:
在用startActivityForResult()來啟動一個Activity時,Intent的寫法與startActivity()是一樣的,沒有不論什麽差別。僅僅是你須要傳遞一個額外的Integer的變量作為啟動參數。當啟動的那個Activity退出時這個參數會被作為回調函數的一個參數,用來區分返回結果。也就是說你啟動Activity時傳遞的參數(requestCode)和返回結果時的那個參數(requestCode)是一致的。
以下是一個調用startActivityForResult()獲取聯系人的樣例:
static final int PICK_CONTACT_REQUEST = 1; // The request code ... private void pickContact() { Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts")); pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST); }
startActivityForResult()函數在Activity源代碼中是這種:
/** * Same as calling [email protected] #startActivityForResult(Intent, int, Bundle)} * with no options. * * @param intent The intent to start. * @param requestCode If >= 0, this code will be returned in * onActivityResult() when the activity exits. * * @throws android.content.ActivityNotFoundException * * @see #startActivity */ public void startActivityForResult(Intent intent, int requestCode) { startActivityForResult(intent, requestCode, null); }這種方法在Activity中進行了重載。startActivityForResult(intent, requestCode, null);方法就不貼出來了。
可是對於這種方法使用時的註意事項我給大家翻譯一下:
- 這種方法僅僅能用來啟動一個帶有返回結果的Activity,Intent的參數設定須要註意一下。你不能啟動一個Activity使用singleTask的launch mode,用singleTask啟動Activity,那個Activity在另外的一個Activity棧中,你會立馬收到RESULT_CANCELED消息。
- 不能在Activity生命周期函數onResume之前調用startActivityForResult()方法,假設你在onResume之前調用了。那麽所在的Activity就無法顯示,直到啟動的那個Activity退出然後返回結果,這是為了避免在又一次定向到另外Activity時窗體閃爍;
接收返回結果:
當startActivityForResult()啟動的Activity完畢任務退出時,系統會回調你調用Activity的onActivityResult()方法。這種方法有三個參數:
- resquestCode : 啟動Activity時傳遞的requestCode。
- resultCode: 表示調用成功或者失敗的變量,值為以下二者之中的一個; /** Standard activity result: operation canceled. */ public static final int RESULT_CANCELED = 0; /** Standard activity result: operation succeeded. */ public static final int RESULT_OK = -1;
- Intent:包括返回內容的Intent;
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request we‘re responding to if (requestCode == PICK_CONTACT_REQUEST) { // Make sure the request was successful if (resultCode == RESULT_OK) { // The user picked a contact. // The Intent‘s data Uri identifies which contact was selected. // Do something with the contact here (bigger example below) } } }
註意:為了正確的處理返回的Intent結果,你須要清楚的了解Intent返回結果的格式。假設是你自己寫的Intent作為返回結果你會非常清楚,可是假設是調用的系統APP(相機。聯系人等),那麽Intent返回結果格式你應該清楚的知道。比方:聯系人應用是返回的聯系人URI。相機返回的是Bitmap數據。
處理返回結果:
以下的代碼是怎樣處理獲取聯系人的結果:@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request it is that we‘re responding to if (requestCode == PICK_CONTACT_REQUEST) { // Make sure the request was successful if (resultCode == RESULT_OK) { // Get the URI that points to the selected contact Uri contactUri = data.getData(); // We only need the NUMBER column, because there will be only one row in the result String[] projection = {Phone.NUMBER}; // Perform the query on the contact to get the NUMBER column // We don‘t need a selection or sort order (there‘s only one result for the given URI) // CAUTION: The query() method should be called from a separate thread to avoid blocking // your app‘s UI thread. (For simplicity of the sample, this code doesn‘t do that.) // Consider using CursorLoader to perform the query. Cursor cursor = getContentResolver() .query(contactUri, projection, null, null, null); cursor.moveToFirst(); // Retrieve the phone number from the NUMBER column int column = cursor.getColumnIndex(Phone.NUMBER); String number = cursor.getString(column); // Do something with the phone number... } } }以下的代碼是處理調用系統相機返回的結果:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); mImageView.setImageBitmap(imageBitmap); } }
獲取啟動Intent:
在被啟動的Activity中你能夠接收啟動這個Activity的Intent,在生命周期範圍內都能調用getIntent()來獲取這個Intent,可是一般都是在onCreat和onStart函數中獲取。以下就是一個獲取Intent的樣例:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Get the intent that started this activity Intent intent = getIntent(); Uri data = intent.getData(); // Figure out what to do based on the intent type if (intent.getType().indexOf("image/") != -1) { // Handle intents with image data ... } else if (intent.getType().equals("text/plain")) { // Handle intents with text ... } }
設置返回Intent:
上面介紹了怎麽在onActivityResult()中處理Intent。可是怎麽在你的應用中設置這個返回Intent呢?假設你想給調用你的Activity返回一個結果能夠通過調用setResult()設置返回內容,然後結束這個Activity。
以下的代碼是一個演示樣例:
// Create intent to deliver some kind of result data Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri"); setResult(Activity.RESULT_OK, result); finish();
以上就是使用Intent在不同Activity進行信息傳遞和溝通的解說,到此Intent系列文章完結。前兩篇文章是關於Intent具體解釋和Intent使用的文章。有什麽不明確的請留言,大家共同學習。共同進步,謝謝。
大家假設對編程感興趣,想了解很多其它的編程知識,解決編程問題,想要系統學習某一種開發知識,我們這裏有java高手。C++/C高 手,windows/Linux高手,android/ios高手,請大家關註我的微信公眾號:程序猿互動聯盟or coder_online。大牛在線為您提供服務。
【Android基礎】利用Intent在Activity之間傳遞數據