我已经确认了相机访问的权限是正确的,但是在更高版本的操作系统(也许API25和更高版本)上,相机没有打开,它只是在调试控制台中给出错误;
W/System.err: java.io.IOException: Permission denied
这就是方法;
public void cameraClicked(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File tempFile = new File(Environment.getExternalStorageDirectory().getPath()+ "/photoTemp.png");
try {
tempFile.createNewFile();
Uri uri = Uri.fromFile(tempFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(takePictureIntent, 2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
它在Android 7及以下版本上确实有效。
编辑-下面的代码现在是正确地打开相机,然而一旦照片被拍摄,它前进到下一个屏幕,但不显示捕获的图像。。。 只是一个黑色的图像。
public void cameraClicked(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String path=this.getExternalCacheDir()+"file.png";
File file=new File(path);
Uri uri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider",file);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(takePictureIntent, 2);
}
w/system.err:java.io.IOException:权限被拒绝
这是因为您通过Android8/9/10将文件创建到外部存储。
如果您的targetSdk为23或更高,则应动态请求权限。 了解更多信息:在运行时请求权限
要获取文件路径,可以使用context.getExternalFilesDir()/context.getExternalCachedir(),例如字符串path=context.GetExternalCachedir()+“File.text”; File File=新文件(路径)如果文件路径为“android/data/app package/File name”,则不需要权限
在Android文档中,您需要写入外部存储,您必须在清单文件中请求WRITE_EXTERNAL_STORAGE权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
如果您使用API23(棉花糖)和更高版本,您需要在运行时请求权限,因为这是一个危险的权限。
if (ContextCompat.checkSelfPermission(
CONTEXT, Manifest.permission.REQUESTED_PERMISSION) ==
PackageManager.PERMISSION_GRANTED) {
// You can use the API that requires the permission.
performAction(...);
} else if (shouldShowRequestPermissionRationale(...)) {
// In an educational UI, explain to the user why your app requires this
// permission for a specific feature to behave as expected. In this UI,
// include a "cancel" or "no thanks" button that allows the user to
// continue using your app without granting the permission.
showInContextUI(...);
} else {
// You can directly ask for the permission.
// The registered ActivityResultCallback gets the result of this request.
requestPermissionLauncher.launch(
Manifest.permission.REQUESTED_PERMISSION);
}
参考源链接
参考
将文件设置为外部文件