ActivityForResult

androidActivity之间的跳转不只是有startActivity(Intent i)的,startActivityForResult(Intentintent, int requestCode)也是常用的方法。


其作用是可以用onActivityResult(int requestCode, int resultCode, Intent data)方法获得请求Activity结束之后的操作。
需要注意三个方法:startActivityForResult(Intentintent, int requestCode),onActivityResult(int requestCode, int resultCode, Intent data),setResult(int resultCode,Intentdata)
例如如下代码:从From跳转至ToB和ToC
From:
if(条件){
Intent intent = new Intent(this, ToB.class);
startActivityForResult(serverIntent, REQUEST_CODE_01);//跳转至ToB
}else{
Intent intent = new Intent(this, ToC.class);
startActivityForResult(serverIntent, 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(Intentintent, int requestCode)的参数,第一个Intent不用说了,需要注意的是第二个,我们用的是REQUEST_CODE_01和REQUEST_CODE_02,其实这个是我们自己定义的一个int型常量,用于标记的,具体作用可在onActivityResult方法里看到,用于判断是从哪个Activity返回的。
ToB:
Intent intent = new Intent();
intent.putExtra(key, value);
setResult(Activity.RESULT_OK, intent);
finish();//结束之后会将结果传回From
ToC:
Intent intent = new Intent();
intent.putExtra(key, value);
setResult(Activity.RESULT_OK, intent);
finish();//结束之后会将结果传回From
setResult的第一个参数对应上面onActivityResult的第二个参数,注意别把onActivityResult的第一个参数与第二个参数搞混淆了,一个是请求标记,一个是返回标记。

以下为android Developer的解释:

Starting an activity for a result
Sometimes, you might want to receive a result from the activity that you start. In that case, start the activity by callingstartActivityForResult()
(instead ofstartActivity()). To then receive the result from the subsequent activity, implement theonActivityResult()callback method. When the subsequent activity is done, it returns a result in anIntentto youronActivityResult()method.

For example, perhaps you want the user to pick one of their contacts, so your activity can do something with the information in that contact. Here's how you can create such an intent and handle the result:

private void pickContact() {      // Create an intent to "pick" a contact, as defined by the content provider URI      Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);      startActivityForResult(intent, PICK_CONTACT_REQUEST);  }    @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {      // If the request went well (OK) and the request was PICK_CONTACT_REQUEST      if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {          // Perform a query to the contact's content provider for the contact's name          Cursor cursor = getContentResolver().query(data.getData(),          new String[] {Contacts.DISPLAY_NAME}, null, null, null);          if (cursor.moveToFirst()) { // True if the cursor is not empty              int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);              String name = cursor.getString(columnIndex);              // Do something with the selected contact's name...          }      }  }  

This example shows the basic logic you should use in youronActivityResult()method in order to handle an activity result. The first condition checks whether the request was successful—if it was, then the resultCode will beRESULT_OK—and whether the request to which this result is responding is known—in this case, the requestCode matches the second parameter sent withstartActivityForResult(). From there, the code handles the activity result by querying the data returned in anIntent(the data parameter).What happens is, aContentResolverperforms a query against a content provider, which returns aCursorthat allows the queried data to be read. For more information, see theContent Providersdocument.

For more information about using intents, see theIntents and Intent Filtersdocument.


两个Activity:ReceiveResult和SendResult。在ReceiveResult中实现onActivityResult(),在此方法中处理SendResult中返回的结果。

注意:

1)在ReceiveResult中定义RequestCode

2)调用startActivityForResult(),用来获取结果

3)在SendResult中用调用setResult()

具体代码如下:

ReceiveResult:

  1. publicclassReceiveResultextendsActivity{
  2. @Override
  3. protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
  4. //TODOAuto-generatedmethodstub
  5. if(requestCode==GET_CODE){
  6. Editabletext=(Editable)mTextView.getText();
  7. if(resultCode==RESULT_CANCELED)
  8. text.append("Cancel");
  9. else{
  10. text.append(data.getAction());
  11. }
  12. }
  13. }
  14. /**Calledwhentheactivityisfirstcreated.*/
  15. @Override
  16. publicvoidonCreate(BundlesavedInstanceState){
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.main);
  19. ButtongetResult=(Button)findViewById(R.id.getButton);
  20. getResult.setOnClickListener(mGetResult);
  21. mTextView=(TextView)findViewById(R.id.results);
  22. mTextView.setText(mTextView.getText(),TextView.BufferType.EDITABLE);
  23. }
  24. /*
  25. *GET_CODErequestCode
  26. */
  27. privatefinalintGET_CODE=0;
  28. privateOnClickListenermGetResult=newOnClickListener(){
  29. publicvoidonClick(Viewv){
  30. Intenti=newIntent(ReceiveResult.this,SendResult.class);
  31. startActivityForResult(i,GET_CODE);
  32. }
  33. };
  34. privateTextViewmTextView;
  35. }

public class ReceiveResult extends Activity { @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub if(requestCode == GET_CODE){ Editable text = (Editable)mTextView.getText(); if(resultCode == RESULT_CANCELED) text.append("Cancel"); else{ text.append(data.getAction()); } } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button getResult = (Button)findViewById(R.id.getButton); getResult.setOnClickListener(mGetResult); mTextView = (TextView)findViewById(R.id.results); mTextView.setText(mTextView.getText(), TextView.BufferType.EDITABLE); } /* * GET_CODE requestCode */ private final int GET_CODE = 0; private OnClickListener mGetResult = new OnClickListener(){ public void onClick(View v){ Intent i = new Intent(ReceiveResult.this, SendResult.class); startActivityForResult(i, GET_CODE); } }; private TextView mTextView; }

SendResult:

  1. publicclassSendResultextendsActivity{
  2. @Override
  3. protectedvoidonCreate(BundlesavedInstanceState){
  4. //TODOAuto-generatedmethodstub
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.sendresult);
  7. Buttonbutton1=(Button)findViewById(R.id.button1);
  8. Buttonbutton2=(Button)findViewById(R.id.button2);
  9. button1.setOnClickListener(mButton1);
  10. button2.setOnClickListener(mButton2);
  11. }
  12. privateOnClickListenermButton1=newOnClickListener(){
  13. publicvoidonClick(Viewv){
  14. setResult(RESULT_OK,(newIntent()).setAction("Button1!"));
  15. finish();
  16. }
  17. };
  18. privateOnClickListenermButton2=newOnClickListener(){
  19. publicvoidonClick(Viewv){
  20. setResult(RESULT_OK,(newIntent()).setAction("Button2!"));
  21. finish();
  22. }
  23. };
  24. }

public class SendResult extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.sendresult); Button button1 = (Button)findViewById(R.id.button1); Button button2 = (Button)findViewById(R.id.button2); button1.setOnClickListener(mButton1); button2.setOnClickListener(mButton2); } private OnClickListener mButton1 = new OnClickListener(){ public void onClick(View v){ setResult(RESULT_OK, (new Intent()).setAction("Button1!")); finish(); } }; private OnClickListener mButton2 = new OnClickListener(){ public void onClick(View v){ setResult(RESULT_OK, (new Intent()).setAction("Button2!")); finish(); } }; }

main.xml:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:gravity="center_horizontal"
  7. >
  8. <TextView
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content"
  11. android:text="@string/hello"
  12. />
  13. <TextViewandroid:id="@+id/results"
  14. android:layout_width="match_parent"android:layout_height="10dip"
  15. android:layout_weight="1"
  16. android:paddingBottom="4dip"
  17. android:background="@drawable/green">
  18. </TextView>
  19. <Button
  20. android:id="@+id/getButton"
  21. android:text="@string/getResult"
  22. android:layout_width="wrap_content"
  23. android:layout_height="wrap_content"
  24. />
  25. </LinearLayout>

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_horizontal" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <TextView android:id="@+id/results" android:layout_width="match_parent" android:layout_height="10dip" android:layout_weight="1" android:paddingBottom="4dip" android:background="@drawable/green"> </TextView> <Button android:id="@+id/getButton" android:text="@string/getResult" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

sendresult.xml:

[c-sharp] view plain copy print ?
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:gravity="center_horizontal"
  7. >
  8. <Button
  9. android:id="@+id/button1"
  10. android:text="@string/sendResult_1"
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. />
  14. <Button
  15. android:id="@+id/button2"
  16. android:text="@string/sendResult_2"
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"
  19. />
  20. </LinearLayout>

<?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_horizontal" > <Button android:id="@+id/button1" android:text="@string/sendResult_1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/button2" android:text="@string/sendResult_2" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

在Unity中,NativeCamera API主要用于直接访问设备的相机功能,如拍照、录像等。如果你想要让用户既能从相机拍摄照片,也能从相册选择已有的图片,通常需要结合原生平台的功能来实现,因为Unity本身并不直接提供这样的交互。 在Android平台上,你可以使用`ActivityForResult`结合`Intent`打开系统的相册选择器。首先,在Unity中创建一个方法来启动相册: ```csharp using UnityEngine; using System.Collections; public class CameraController : MonoBehaviour { public void TakePictureFromAlbum() { // Android部分 if (Application.platform == RuntimePlatform.Android) { Intent intent = new Intent(Intent.ActionPick); intent.setType("image/*"); startActivityForResult(intent, 0); } // iOS部分 (未直接提供类似API,需通过原生插件处理) else if (Application.platform == RuntimePlatform.IPhonePlayer) { Debug.LogError("TakePictureFromAlbum is not supported on iOS directly."); } } protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { // 在这里处理相册选择的结果 if (requestCode == 0 && resultCode ==.Result.Ok) { // 获取选中的图片文件路径或其他相关信息 string selectedImagePath = data.Data.ToString(); // 然后可以将路径传递给NativeCamera拍照函数,或者做进一步处理 } } } ``` 在iOS上,你需要通过Objective-C或Swift的原生插件来实现相册选择,并在Unity中触发这个操作。由于Unity不支持直接访问iOS的相册,所以这部分需要外部插件的支持。 注意,这只是一个基础示例,实际应用中你还需要处理异常情况和权限请求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值