我开发的应用程序用到了SDCard来保存Camera所拍摄的照片。
Manifest 文件中需要配置的权限和特征(feature)如下:
(1)<uses-permission android:name="android.permission.CAMERA" /> // 程序具有访问手持设备照相机的权限
(2)<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />//程序具有访问外部存储器(SDCard)的权限
(3)<uses-feature
android:name="android.hardware.camera"
android:required="false" />
上面这个属性就是手持设备必须具有照相机功能。这个属性就是Google Play用来过滤手持设备的,如果设备没有摄像头,这个APP就不会显示,你也就不能安装这个
应用程序。
应用程序的大致代码如下:
变量定义如下:
// get picture from camera
private static final int PHOTO_WITH_CAMERA = 1010;
// picture file
private File pictureFile;
当触发一个事件(比如说点击一个按钮时,开启Camera),代码如下:
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//MediaStore.ACTION_IMAGE_CAPTURE 调用Camera 得到一个图片并返回这个图片
pictureFile = new File(PHOTO_DIR, getPhotoFileName());//getPhotoFileName() 生成的图片名称
try {
pictureFile.createNewFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(pictureFile));//将图片保存,名称为上面生成的图片名称
}
catch (IOException e) {
e.printStackTrace();
}
startActivityForResult(intent, PHOTO_WITH_CAMERA);
}
//According to current time to generate the name of the picture file
private String getPhotoFileName() {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
return dateFormat.format(date) + ".jpg";
}
这种解决方案有个小小问题,就是点击自己应用程序按钮时候的时间(文件名称根据它产生),打开照相机后可能过一段时间再照相(这时候才保存图片,名称是前面提到的)。
上面的文字,红色字体部分为注释。
希望对您有所帮助,共同学习吧。