intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//create a intent to take picture fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name // start the image capture Intent startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { // Image captured and saved to fileUri specified in the Intent Toast.makeText(this, "Image saved to:
" + data.getData(), Toast.LENGTH_LONG).show(); } else if (resultCode == RESULT_CANCELED) { // User cancelled the image capture } else { // Image capture failed, advise user } } }
/** Create a file Uri for saving an image or video */ private static Uri getOutputMediaFileUri(int type){ return Uri.fromFile(getOutputMediaFile(type)); } /** Create a File for saving an image or video */ private static File getOutputMediaFile(int type){ // To be safe, you should check that the SDCard is mounted // using Environment.getExternalStorageState() before doing this. File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "MyCameraApp"); // This location works best if you want the created images to be shared // between applications and persist after your app has been uninstalled. if (! mediaStorageDir.exists()){ if (! mediaStorageDir.mkdirs()){ Log.d("MyCameraApp", "failed to create directory"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile = null; if (type == MEDIA_TYPE_IMAGE){ mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg"); } return mediaFile; } }第四步:运行程序。如果拍完照返回的时候,程序崩溃,查看日志出现如下错误:java.lang.RuntimeException: Failure delivering resultResultInfo{who=null, request=100, result=-1, data=null} to activity在AndroidManifest.xml中的activity元素加入android:launchMode="singleInstance"属性即可解决该问题。拍完照之后,可以在SD卡中的Pictures/MyCameraApp目录下找到保存的照片。更多详情见请继续阅读下一页的精彩内容: http://www.linuxidc.com/Linux/2013-11/92892p2.htm相关阅读:Android开发:Camera初探——控制摄像头拍照 http://www.linuxidc.com/Linux/2013-01/78025.htmAndroid Camera调用流程 http://www.linuxidc.com/Linux/2012-06/61676.htmAndroid图像处理简介の使用内置Camera应用程序进行图像捕获 http://www.linuxidc.com/Linux/2012-02/53914.htmAndroid开发之初识Camera图像采集 http://www.linuxidc.com/Linux/2011-08/41561.htmAndroid平台接收基于 PC Camera 直播流的方案 http://www.linuxidc.com/Linux/2010-08/27713.htm