2016-07-21 37 views
1

有人可以解释什么是相机请求代码?相机请求代码在Android中的含义是什么

我们为什么要使用它?

我正在尝试在Android的做法,我看到的代码。

这是我做的练习的代码;

public class imageActivity extends AppCompatActivity { 

    Button image; 
    private static final int CAMERA_REQUEST = 1888; 
    private ImageView imageView; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_resim); 

     imageView = (ImageView)this.findViewById(R.id.imageView1); 
     image = (Button) findViewById(R.id.capture); 

     image.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
       startActivityForResult(cameraIntent, CAMERA_REQUEST); 
      } 
     }); 


    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { 
      Bitmap photo = (Bitmap) data.getExtras().get("data"); 
      imageView.setImageBitmap(photo); 
     } 
    } 
} 
+1

通过这个的答案 - https://developer.android.com/training/basics/intents/result .html –

+0

请为您的问题添加更多的细节。你在问什么CAMERA_REQUEST的价值? –

+0

@JosephRosson是 – kinyas

回答

4

你可以在一个单一的活动,以startActivityForResult()它允许不同Intent下做不同的动作几个电话。使用请求代码来确定您要返回的是哪个Intent

例如:

可以启动两项活动的结果:

private static final int CAMERA_REQUEST = 1888; 
private static final int GALLERY_REQUEST = 1889; 
startActivityForResult(cameraIntent, CAMERA_REQUEST); 
startActivityForResult(cameraIntent, GALLERY_REQUEST); 

并在onActivityForResult()

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { 
     //Do stuff with the camara data result 
    } 
    else if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) { 
     //Do stuff with the gallery data result 
    } 
} 

请注意,private static final int s为完全任意。

+1

谢谢。我像在我的问题中回答的其他人一样拒绝你的回答。 – kinyas

+0

不客气!您可以将其中的一个设置为避免接收更多帖子的答案。 :d –

1

只是在接收响应时检测/确认REQUEST,我们使用CAMERA_REQUEST。

1

它用来接收相机意图结果

if (requestCode == CAMERA_REQUEST) { 
    if (resultCode == RESULT_OK) { 
     // Image captured and saved to fileUri specified in the Intent 

    } else if (resultCode == RESULT_CANCELED) { 
     // User cancelled the image capture 
    } else { 
     // Image capture failed, advise user 
    } 
} 

See Official Documentation

1

这是什么意思:

当你开始对结果的活动,例如要求相机把你的照片,然后将其返回到您的电话活动,传递给它一个唯一的整数值,像100001或任何你有不在该类中使用。

因此,简而言之,CAMERA_REQUEST可能是你在你的类像这样定义的任何值:请求从相机中的照片时

private static final int CAMERA_REQUEST = 10001; 

现在,因为你通过它,你会用它来检查requestCode,因为如果它是摄像机本身,它将不得不匹配它。

我希望这可以帮助你理解。

1

onActivityResult()可以处理更多的一个回复,就像您启动意图从图库中选取图像一样,其结果也会在onActivityResult()中收到。

所以要检测我们得到的结果,我们添加一个标识符,这就是为什么我们使用CAMERA_REQUEST。希望你能理解。

相关问题