btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 利用系统自带的相机应用:拍照
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// create a file to save the image
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
// 此处这句intent的值设置关系到后面的onActivityResult中会进入那个分支,即关系到data是否为null,如果此处指定,则后来的data为null
// set the image file name
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(LOG_TAG, "onActivityResult: requestCode: " + requestCode
+ ", resultCode: " + requestCode + ", data: " + data);
// 如果是拍照
if (CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE == requestCode) {
Log.d(LOG_TAG, "CAPTURE_IMAGE");
if (RESULT_OK == resultCode) {
Log.d(LOG_TAG, "RESULT_OK");
// Check if the result includes a thumbnail Bitmap
if (data != null) {
System.out.println("1");
// 没有指定特定存储路径的时候
Log.d(LOG_TAG,
"data is NOT null, file on default position.");
// 指定了存储路径的时候(intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);)
// Image captured and saved to fileUri specified in the
// Intent
Toast.makeText(this, "Image saved to:\n" + data.getData(),
Toast.LENGTH_LONG).show();
if (data.hasExtra("data")) {
Bitmap thumbnail = data.getParcelableExtra("data");
System.out.println("thumbnail:" + thumbnail);
imageView.setImageBitmap(thumbnail);
}
} else {
Log.d(LOG_TAG,
"data IS null, file saved on target position.");
// If there is no thumbnail image data, the image
// will have been stored in the target output URI.
// Resize the full image to fit in out image view.
System.out.println("1");
int width = imageView.getWidth();
int height = imageView.getHeight();
System.out.println("2");
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
factoryOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(fileUri.getPath(), factoryOptions);
int imageWidth = factoryOptions.outWidth;
int imageHeight = factoryOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(imageWidth / width, imageHeight
/ height);
// Decode the image file into a Bitmap sized to fill the
// View
factoryOptions.inJustDecodeBounds = false;
factoryOptions.inSampleSize = scaleFactor;
factoryOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
factoryOptions);
imageView.setImageBitmap(bitmap);
}
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
// 如果是录像
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
Log.d(LOG_TAG, "CAPTURE_VIDEO");
if (resultCode == RESULT_OK) {
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
} else {
// Video capture failed, advise user
}
}
}
源码下载链接:http://download.csdn.net/detail/msn465780/5771643