所以,我有以下代码打开相机,捕获图像并将其保存在SD卡上。
public void getPhotoFromCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory()
+ File.separator
+ getString(R.string.directory_name_corp_chat)
+ File.separator
+ getString(R.string.directory_name_temp)
);
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
try {
mediaFile = File.createTempFile(
"TEMP_FULL_IMG_" + timeStamp,
".jpg",
mediaStorageDir
);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mediaFile));
startActivityForResult(takePictureIntent, PICK_FROM_CAMERA);
} catch (IOException e) {
e.printStackTrace();
}
}
private void performCrop(Uri picUri) {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 128);
cropIntent.putExtra("outputY", 128);
// retrieve data on return
cropIntent.putExtra("return-data", true);
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory()
+ File.separator
+ getString(R.string.directory_name_corp_chat)
+ File.separator
+ getString(R.string.directory_name_temp)
);
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
try {
croppedFile = File.createTempFile(
"TEMP_CROPPED_IMG_" + timeStamp,
".jpg",
mediaStorageDir
);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(croppedFile));
startActivityForResult(cropIntent, PIC_CROP);
} catch (IOException e) {
e.printStackTrace();
}
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_CAMERA) {
if (resultCode == RESULT_OK) {
performCrop(Uri.fromFile(mediaFile));
} else {
Log.i("Camera", "result cancel. Hence, deleting file: " + mediaFile.getPath());
Log.i("File deleted ", mediaFile.delete() + "");
}
}
if (requestCode == PICK_FROM_GALLERY) {
if (resultCode == RESULT_OK) {
performCrop(data.getData());
} else {
Log.i("Gallery", "result cancel");
}
}
if (requestCode == PIC_CROP) {
if (resultCode == RESULT_OK) {
imageView.setImageBitmap(BitmapFactory.decodeFile(croppedFile.getAbsolutePath()));
if (mediaFile != null) {
Log.i("Camera", "result cancel. Hence, deleting file: " + mediaFile.getPath());
Log.i("File deleted ", mediaFile.delete() + "");
}
} else {
if (croppedFile != null) {
Log.i("Camera", "result cancel. Hence, deleting file: " + croppedFile.getPath());
Log.i("File deleted ", croppedFile.delete() + "");
}
if (mediaFile != null) {
Log.i("Camera", "result cancel. Hence, deleting file: " + mediaFile.getPath());
Log.i("File deleted ", mediaFile.delete() + "");
}
}
}
}
在Android 6.0下,一切都如预期的那样完美。但它在Android 6.0 Marshmallow上不起作用。事实上,它甚至没有打开相机:(
我不知道是否必须为棉花糖做一些特别的事情。我也没有收到任何错误,我可以在这里发布。请帮帮我。
感谢。
答案 0 :(得分:34)
所以,我完成了如下任务:
对于检查权限,我创建了一个单独的类,如下所示:
public class MarshMallowPermission {
public static final int RECORD_PERMISSION_REQUEST_CODE = 1;
public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
public static final int CAMERA_PERMISSION_REQUEST_CODE = 3;
Activity activity;
public MarshMallowPermission(Activity activity) {
this.activity = activity;
}
public boolean checkPermissionForRecord(){
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
public boolean checkPermissionForExternalStorage(){
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
public boolean checkPermissionForCamera(){
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
public void requestPermissionForRecord(){
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.RECORD_AUDIO)){
Toast.makeText(activity, "Microphone permission needed for recording. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.RECORD_AUDIO},RECORD_PERMISSION_REQUEST_CODE);
}
}
public void requestPermissionForExternalStorage(){
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(activity, "External Storage permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
}
}
public void requestPermissionForCamera(){
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)){
Toast.makeText(activity, "Camera permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.CAMERA},CAMERA_PERMISSION_REQUEST_CODE);
}
}
}
然后,获取
...
MarshMallowPermission marshMallowPermission = new MarshMallowPermission(this);
...
public void getPhotoFromCamera() {
if (!marshMallowPermission.checkPermissionForCamera()) {
marshMallowPermission.requestPermissionForCamera();
} else {
if (!marshMallowPermission.checkPermissionForExternalStorage()) {
marshMallowPermission.requestPermissionForExternalStorage();
} else {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory()
+ File.separator
+ getString(R.string.directory_name_corp_chat)
+ File.separator
+ getString(R.string.directory_name_images)
);
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
try {
mediaFile = File.createTempFile(
"IMG_" + timeStamp, /* prefix */
".jpg", /* suffix */
mediaStorageDir /* directory */
);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mediaFile));
startActivityForResult(takePictureIntent, PICK_FROM_CAMERA);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
答案 1 :(得分:7)
从Android 6.0(API级别23)开始,用户授予权限 应用程序运行时的应用程序,而非安装应用程序时的应用程序。这个 方法简化了应用安装过程,因为用户没有 需要在安装或更新应用程序时授予权限。它也是 让用户更好地控制应用程序的功能;例如, 用户可以选择让相机应用程序访问相机,但不能 到设备位置。用户可以撤消任何权限 时间,转到应用程序的“设置”屏幕。
系统权限分为两类,普通和 危险:
正常权限不会直接影响用户的隐私。如果你的 应用程序列出其清单中的正常权限,系统授予 自动许可。
危险权限可以为应用提供 访问用户的机密数据。如果您的应用列出正常 在其清单中的权限,系统授予权限 自动。如果列出危险权限,则用户必须这样做 明确批准您的应用。
WRITE_EXTERNAL_STORAGE
属于Dangerous类别,因此您需要在致电mediaStorageDir.mkdirs()
或File.createTempFile
之前向用户请求权限,否则您会因此异常而崩溃:
W/System.err: java.io.IOException: open failed: EACCES (Permission denied)
W/System.err: at java.io.File.createNewFile(File.java:939)
W/System.err: at java.io.File.createTempFile(File.java:1004)
W/System.err: at com.example.MainActivity.getPhotoFromCamera(MainActivity.java:98)
W/System.err: at com.example.MainActivity.onCreate(MainActivity.java:48)
W/System.err: at android.app.Activity.performCreate(Activity.java:6237)
W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476
W/System.err: at android.app.ActivityThread.-wrap11(ActivityThread.java)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:148)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission
W/System.err: at libcore.io.Posix.open(Native Method)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
W/System.err: at java.io.File.createNewFile(File.java:932)
W/System.err: ... 15 more