android Activity之间的跳转不只是有startActivity(Intent i)的,startActivityForResult(Intent intent, int requestCode)也是常用的

方法。

在一个主界面(主Activity)上能连接往许多不同子功能模块(子Activity上去),当子模块的事情做完之后就回到主界面,或许还同时返回一些子模块完成的数据交给主Activity处理。这个时候就要用到回调函数onActivityResult()。 

 

需要注意三个方法:startActivityForResult(Intent intent, int requestCode),onActivityResult(int requestCode, int resultCode, Intent data),setResult(int resultCode, Intent data).

 

例如如下代码:从From跳转至ToB和ToC

From:

if(条件){

Intent intent = new Intent(this, ToB.class);

startActivityForResult(intent, REQUEST_CODE_01);//跳转至ToB

}else{

Intent intent = new Intent(this, ToC.class);

startActivityForResult(intent, REQUEST_CODE_02);//跳转至ToC

}

 

public void onActivityResult(int requestCode, int resultCode, Intent data){

switch (requestCode) {//请求标记

case REQUEST_CODE_01:

                        if(resultCode==Activity.RESULT_OK)

                        //do something

                        break;

                case REQUEST_CODE_02:

//do something

                        break;

}

}

 

startActivityForResult(Intent intent, int requestCode)的参数,需要注意的是第二个,我们用的是REQUEST_CODE_01和REQUEST_CODE_02,其实这个是我们自己定义的一个int型常量,用于标记的,具体作用可在onActivityResult方法里看到,用于判断是哪个Activity传来的。

requestCode是请求标记, resultCode是返回标记。

 

ToB:

Intent intent = new Intent();

intent.putExtra(key, value);

setResult(Activity.RESULT_OK, intent);

finish();//结束之后会将结果传回From

这里的跳转回去,只能用setResult(int resultCode, Intent data)方法,否则会出错,无法从onActivityResult(int requestCode, int resultCode, Intent data)中的data接收到传回来的数据。

ToC:

Intent intent = new Intent();

intent.putExtra(key, value);

setResult(Activity.RESULT_OK, intent);

finish();//结束之后会将结果传回From

 

setResult的第一个参数对应上面onActivityResult的第二个参数。

实例的一个效果:

 

点击搜索按钮,找到DianXin。

 

源码:

 

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  3.     android:layout_width="fill_parent" 
  4.     android:layout_height="fill_parent" 
  5.     android:orientation="vertical" > 
  6.  
  7.     <TextView 
  8.         android:id="@+id/mTextView" 
  9.         android:layout_width="fill_parent" 
  10.         android:layout_height="wrap_content" 
  11.         android:text="我的联系人" /> 
  12.     <EditText 
  13.         android:id="@+id/mEditText01" 
  14.         android:layout_width="fill_parent" 
  15.         android:layout_height="wrap_content" 
  16.         android:text="姓名" 
  17.         /> 
  18.     <EditText 
  19.         android:id="@+id/mEditText02" 
  20.         android:layout_width="fill_parent" 
  21.         android:layout_height="wrap_content" 
  22.         android:text="电话号码" 
  23.         /> 
  24.     <Button 
  25.         android:id="@+id/mButton" 
  26.         android:layout_width="wrap_content" 
  27.         android:layout_height="wrap_content" 
  28.         android:text="搜索" 
  29.         /> 
  30. </LinearLayout> 

 

  1. package com.xc.ex05_10; 
  2.  
  3. import android.app.Activity; 
  4. import android.content.Intent; 
  5. import android.database.Cursor; 
  6. import android.net.Uri; 
  7. import android.os.Bundle; 
  8. import android.provider.ContactsContract; 
  9. import android.view.View; 
  10. import android.widget.Button; 
  11. import android.widget.EditText; 
  12. import android.widget.TextView; 
  13. import android.widget.Toast; 
  14.  
  15. public class EX05_10 extends Activity { 
  16.     private TextView mTextView; 
  17.     private Button mButton; 
  18.     private EditText mEditText01; 
  19.     private EditText mEditText02; 
  20.     //回传标志 
  21.     private static final int PICK_CONTACT_SUBACTIVITY = 2
  22.     /** Called when the activity is first created. */ 
  23.     @Override 
  24.     public void onCreate(Bundle savedInstanceState) { 
  25.         super.onCreate(savedInstanceState); 
  26.         setContentView(R.layout.main); 
  27.          
  28.         mTextView = (TextView)findViewById(R.id.mTextView); 
  29.         mEditText01 = (EditText)findViewById(R.id.mEditText01); 
  30.         mEditText02 = (EditText)findViewById(R.id.mEditText02); 
  31.         mButton = (Button)findViewById(R.id.mButton); 
  32.          
  33.         mButton.setOnClickListener(new Button.OnClickListener() { 
  34.              
  35.             @Override 
  36.             public void onClick(View v) { 
  37.                 // TODO Auto-generated method stub 
  38.                 startActivityForResult(new Intent(Intent.ACTION_PICK,  
  39.                         android.provider.ContactsContract.Contacts.CONTENT_URI),  
  40.                         PICK_CONTACT_SUBACTIVITY); 
  41.             } 
  42.         }); 
  43.          
  44.     } 
  45.     //向新打开的Activity传递参数 
  46.     //resultCode为回传的标记 
  47.     //data为B(新打开的Activity)中回传的Intent 
  48.     @Override 
  49.     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
  50.         // TODO Auto-generated method stub 
  51.         try
  52.             switch (requestCode) { 
  53.             case PICK_CONTACT_SUBACTIVITY: 
  54.                 final Uri uriRet = data.getData(); 
  55.                 if(uriRet != null){ 
  56.                     try
  57.                         //必须要有android.permission.READ_CONTACTS权限 
  58.                         Cursor c = managedQuery(uriRet, nullnullnullnull);   
  59.                         c.moveToFirst(); 
  60.                         String strName = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 
  61.                         mEditText01.setText(strName); 
  62.                         //取得联系人的电话 
  63.                         int contactId = c.getInt(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); 
  64.                         Cursor phones = getContentResolver().query( 
  65.                                 ContactsContract.CommonDataKinds.Phone.CONTENT_URI,  
  66.                                 null,  
  67.                                 ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "+ contactId,  
  68.                                 nullnull); 
  69.                         StringBuffer sb = new StringBuffer(); 
  70.                         int typePhone, resType; 
  71.                         String numPhone; 
  72.                         if(phones.getCount() > 0){ 
  73.                             phones.moveToFirst(); 
  74.                             typePhone = phones.getInt( 
  75.                                     phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)); 
  76.                             numPhone = phones.getString( 
  77.                                     phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
  78.                             resType = ContactsContract.CommonDataKinds.Phone.getTypeLabelResource(typePhone); 
  79.                             sb.append(getString(resType) + ":" + numPhone + "\n"); 
  80.                             mEditText02.setText(numPhone); 
  81.                         }else { 
  82.                             sb.append("no Phone number found");  
  83.                         } 
  84.                          Toast.makeText   
  85.                           (this, sb.toString(), Toast.LENGTH_SHORT).show(); 
  86.                     }catch (Exception e) { 
  87.                         mTextView.setText(e.toString());    
  88.                         e.printStackTrace(); 
  89.                     } 
  90.                 } 
  91.                 break
  92.             default
  93.                 break
  94.             } 
  95.         }catch (Exception e) { 
  96.             e.printStackTrace(); 
  97.         } 
  98.         super.onActivityResult(requestCode, resultCode, data);   
  99.     } 

 

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  3.     package="com.xc.ex05_10" 
  4.     android:versionCode="1" 
  5.     android:versionName="1.0" > 
  6.  
  7.     <uses-sdk android:minSdkVersion="8" /> 
  8.     <uses-permission android:name="android.permission.READ_CONTACTS"/>  
  9.     <application 
  10.         android:icon="@drawable/ic_launcher" 
  11.         android:label="@string/app_name" > 
  12.         <activity 
  13.             android:label="@string/app_name" 
  14.             android:name=".EX05_10" > 
  15.             <intent-filter > 
  16.                 <action android:name="android.intent.action.MAIN" /> 
  17.  
  18.                 <category android:name="android.intent.category.LAUNCHER" /> 
  19.             </intent-filter> 
  20.         </activity> 
  21.     </application> 
  22.  
  23. </manifest> 

 例子②:

布局文件为两个按钮,不再给出。

  1. package com.example.intentproject; 
  2.  
  3. import android.app.Activity; 
  4. import android.content.Intent; 
  5. import android.os.Bundle; 
  6. import android.view.View; 
  7. import android.widget.Button; 
  8. import android.widget.Toast; 
  9.  
  10. public class SenderActivity extends Activity{ 
  11.  
  12.     private static final int MY_REQUEST_CODE = 1
  13.     private Button sender; 
  14.     @Override 
  15.     protected void onCreate(Bundle savedInstanceState) { 
  16.         super.onCreate(savedInstanceState); 
  17.         setContentView(R.layout.sender); 
  18.         sender = (Button)findViewById(R.id.sender); 
  19.          
  20.         sender.setOnClickListener(new Button.OnClickListener() { 
  21.              
  22.             @Override 
  23.             public void onClick(View v) { 
  24.                 Intent intent = new Intent(SenderActivity.this, RecieverActivity.class); 
  25.                 startActivityForResult(intent, MY_REQUEST_CODE); 
  26.             } 
  27.         }); 
  28.     } 
  29.      
  30.     @Override 
  31.     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
  32.         switch(requestCode){ 
  33.             case MY_REQUEST_CODE: 
  34.                 // 取出数据 
  35.                 String info=data.getStringExtra("data2"); 
  36.                 Toast.makeText(this, info, Toast.LENGTH_LONG).show(); 
  37.                 break
  38.         } 
  39.         switch (resultCode) { 
  40.             case Activity.RESULT_CANCELED: 
  41.                 Toast.makeText(this"处理:"+String.valueOf(Activity.RESULT_CANCELED), Toast.LENGTH_LONG).show();  
  42.                 break
  43.             case Activity.RESULT_OK: 
  44.                 Toast.makeText(this"处理:"+String.valueOf(Activity.RESULT_OK), Toast.LENGTH_LONG).show();    
  45.                 break
  46.             case Activity.RESULT_FIRST_USER: 
  47.                 String info=data.getStringExtra("data2"); 
  48.                 Toast.makeText(this, info, Toast.LENGTH_LONG).show(); 
  49.                 break
  50.      
  51.             default
  52.                 break
  53.         } 
  54.         super.onActivityResult(requestCode, resultCode, data); 
  55.     } 

  1. package com.example.intentproject; 
  2.  
  3. import android.app.Activity; 
  4. import android.content.Intent; 
  5. import android.os.Bundle; 
  6. import android.widget.Button; 
  7.  
  8. public class RecieverActivity extends Activity{ 
  9.  
  10.     private Button reciever; 
  11.     @Override 
  12.     protected void onCreate(Bundle savedInstanceState) { 
  13.         super.onCreate(savedInstanceState); 
  14.         setContentView(R.layout.reciever); 
  15.         reciever = (Button)findViewById(R.id.reciever); 
  16.          
  17.         Intent intent = new Intent(); 
  18.         intent.putExtra("data2""给你回送数据!礼尚往来!"); 
  19.         this.setResult(Activity.RESULT_FIRST_USER, intent); 
  20.     } 

RecieverActivity.java中也可以写成:

  1. Intent intent=this.getIntent(); 
  2.         //返回数据 
  3.         intent.putExtra("data2""给你回送数据!礼尚往来!"); 
  4.         this.setResult(Activity.RESULT_FIRST_USER, intent); 

也可以在SenderActivity.java文件中一开始就传递参数,在按钮响应事件中写成:

 

  1. sender.setOnClickListener(new View.OnClickListener() { 
  2.             @Override 
  3.             public void onClick(View v) { 
  4.  
  5.                 Intent intent = new Intent(SenderActivity.this
  6.                         ReciverActivity.class); 
  7.                 intent.putExtra("data""给你发送数据!"); 
  8.                 // 这种启动方式 ,表示是有返回结果的 
  9.                 SenderActivity.this.startActivityForResult(intent, 
  10.                         MY_REQUEST_CODE); 
  11.             } 
  12.         }); 

RecieverActivity.java中写:

  1. Intent intent=this.getIntent(); 
  2.         String info=intent.getStringExtra("data"); 
  3.         Toast.makeText(this, info, Toast.LENGTH_LONG).show(); 
  4.         //返回数据 
  5.         intent.putExtra("data2""给你回送数据!礼尚往来!"); 
  6.         this.setResult(Activity.RESULT_FIRST_USER, intent);