我正在尝试创建一个捕获一些图像然后通过电子邮件发送的应用程序
我的问题是:
我是否需要为每个API创建不同的代码来访问摄像头和外部存储?
因为我已创建此代码并在我的手机上正常工作(API 22):
public void startCameraIntent(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takenPicture = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "image.jpg");
Uri tempURI = Uri.fromFile(takenPicture);
intent.putExtra(MediaStore.EXTRA_OUTPUT, tempURI);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
startActivityForResult(intent, CAMERA_INTENT);
}
在此代码中,我尝试将捕获的图像保存在takenPicture文件中并保存在设备的特定位置。
当我尝试在具有更高API(23或24)的其他设备上运行此代码时,我得到Permission Denied for CAMERA
,尽管我已在AndroidManifest.xml文件中添加了权限:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera.any" android:required="true"/>
有人可以向我说明我还在学习,我真的想知道如何让这个代码适用于任何设备。
当我第一次创建项目时,我将Lollipop设为我最低的Android系统。
答案 0 :(得分:0)
在Marshmallow下方,安装时会隐式授予所有权限。但是在API 23及更高版本上需要明确地询问用户在运行时所需的权限。
以下是官方documentation的示例。
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.CAMERA)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
arrayOf(Manifest.permission.CAMERA),
MY_PERMISSIONS_REQUEST_CAMERA)
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}