btn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 利用系統內建的相機應用:拍照Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// create a file to save the imagefileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);// 此處這句intent的值設定關係到後面的onActivityResult中會進入那個分支,即關係到data是否為null,如果此處指定,則後來的data為null// set the image file nameintent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);startActivityForResult(intent,CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);}});@Overrideprotected 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 Bitmapif (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// IntentToast.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 imageint scaleFactor = Math.min(imageWidth / width, imageHeight/ height);// Decode the image file into a Bitmap sized to fill the// ViewfactoryOptions.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