我有这个代码,允许用户访问相机拍照并从图库中选择图像,它适用于运行Android 5.1.1的Sony Xperia Z3。
我现在已经升级到运行Android 6.0的Nexus 5X,但是当我尝试使用相机或保存图像时,我会收到任何帮助吗?
我使用相机的代码
Intent CameraImage = new Intent("android.media.action.IMAGE_CAPTURE");
Intent SelectedCameraImage = Intent.createChooser(CameraImage, "Take A Photo With");
startActivityForResult(SelectedCameraImage, SELECTED);
我的结果处理程序
public void onActivityResult(int RequestCode, int ResultCode, Intent Data) {
if (ResultCode == RESULT_OK) {
if (RequestCode == SELECTED) {
Uri SelectedImageUri = Data.getData();
SelectedImagePath = getPath(SelectedImageUri);
Log.d("DatabaseOperations", "Image Path : " + SelectedImagePath);
Img.setImageURI(SelectedImageUri);
try {
FileInputStream FileInpStream = new FileInputStream(SelectedImagePath);
BufferedInputStream BufInputStream = new BufferedInputStream(FileInpStream);
DBByte = new byte[BufInputStream.available()];
BufInputStream.read(DBByte);
Log.d("DatabaseOperations", "Image Size : " + DBByte.length + " KB");
}
catch (IOException e) {
Log.d("DatabaseOperations", "Error : " + SelectedImagePath);
Log.d("DatabaseOperations", e.getMessage(), e);
}
}
}
}
public String getPath(Uri Uris) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor Cursor = managedQuery(Uris, projection, null, null, null);
int ColumnIndex = Cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
Cursor.moveToFirst();
return Cursor.getString(ColumnIndex);
}
我的清单权限
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.CAMERA" />
错误(Logcat)
FATAL EXCEPTION: main
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: Process: rajancorporations.database, PID: 3768
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.google.android.GoogleCamera/com.android.camera.CaptureActivity } from ProcessRecord{c9f94d7 3768:rajancorporations.database/u0a80} (pid=3768, uid=10080) with revoked permission android.permission.CAMERA
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Parcel.readException(Parcel.java:1620)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Parcel.readException(Parcel.java:1573)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:2658)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.Instrumentation.execStartActivity(Instrumentation.java:1507)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3930)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3890)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:784)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at rajancorporations.database.Reg$2.onClick(Reg.java:75)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.view.View.performClick(View.java:5204)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:21153)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
答案 0 :(得分:3)
这是我从相机或图库中拍摄图像的完整代码,它在棉花糖中与其他人一起正常工作。
我在这里宣布Varriables
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_REQUEST = 1;
private static final int REQUEST_ACESS_STORAGE=3;
private static final int REQUEST_ACESS_CAMERA=2;
private Uri uri;
这里我有一些获得marshmallow许可的方法
public static boolean checkPermission(String permission, Context context) {
int statusCode = ContextCompat.checkSelfPermission(context, permission);
return statusCode == PackageManager.PERMISSION_GRANTED;
}
public static void requestPermission(AppCompatActivity activity, String[] permission, int requestCode) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission[0])) {
Toast.makeText(activity, "Application need permission", Toast.LENGTH_SHORT).show();
}
ActivityCompat.requestPermissions(activity, permission, requestCode);
}
public static void requestPermission(Fragment fragment, String[] permission, int requestCode) {
fragment.requestPermissions(permission, requestCode);
}
我的onclick方法
if (v.getId()==R.id.idOfPhoto){
handleCamera();
}
手柄相机方法的详细信息
private void handleCamera(){
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
if (checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, this)) {
startDilog();
}else{
requestPermission(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_ACESS_STORAGE);
}
}else{
startDilog();
}
}
startdilog方法
private void startDilog() {
AlertDialog.Builder myAlertDilog = new AlertDialog.Builder(YourActivity.this);
myAlertDilog.setTitle("Upload picture option..");
myAlertDilog.setMessage("Where to upload picture????");
myAlertDilog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent picIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
picIntent.setType("image/*");
picIntent.putExtra("return_data",true);
startActivityForResult(picIntent,GALLERY_REQUEST);
}
});
myAlertDilog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
if(checkPermission(Manifest.permission.CAMERA,YourActivity.this)){
openCameraApplication();
}else{
requestPermission(YourActivity.this,new String[]{Manifest.permission.CAMERA},REQUEST_ACESS_CAMERA);
}
}else{
openCameraApplication();
}
}
});
myAlertDilog.show();
}
openCameraApplication方法
private void openCameraApp() {
Intent picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (picIntent.resolveActivity(getPackageManager())!= null){
startActivityForResult(picIntent, CAMERA_REQUEST);
}
}
其余代码
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST) {
if (resultCode == RESULT_OK) {
if (data != null) {
uri = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
options.inSampleSize =calculateInSampleSize(options, 100, 100);
options.inJustDecodeBounds = false;
Bitmap image = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
imageview.setImageBitmap(image);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (data.hasExtra("data")) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
uri = getImageUri(YourActivity.this, bitmap);
File finalFile = new File(getRealPathFromUri(uri));
imageview.setImageBitmap(bitmap);
} else if (data.getExtras() == null) {
Toast.makeText(getApplicationContext(),
"No extras to retrieve!", Toast.LENGTH_SHORT)
.show();
BitmapDrawable thumbnail = new BitmapDrawable(
getResources(), data.getData().getPath());
owner_pic.setImageDrawable(thumbnail);
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
private String getRealPathFromUri(Uri tempUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = this.getContentResolver().query(tempUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private Uri getImageUri(YourActivity youractivity, Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String path = MediaStore.Images.Media.insertImage(youractivity.getContentResolver(), bitmap, "Title", null);
return Uri.parse(path);
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==REQUEST_ACESS_STORAGE && grantResults[0]== PackageManager.PERMISSION_GRANTED){
startDilog();
}
if(requestCode==REQUEST_ACESS_CAMERA && grantResults[0]==PackageManager.PERMISSION_GRANTED){
openCameraApp();
}
}
它在所有设备上运行良好..
答案 1 :(得分:1)
首先,您假设Data.getData()
在这里有意义。 There is no Uri
returned by ACTION_IMAGE_CAPTURE
, according to the specification。您可以选择提供EXTRA_OUTPUT
(在这种情况下,图片应该是您在该额外内容中指明的位置),或者从Data.getExtra("data")
获取缩略图。可能会有一些相机应用返回Uri
。但是有超过 8,000个 Android设备型号,有数百个(如果不是数千个)不同的默认相机应用程序。用户可能还会让您的请求由第三方相机应用处理。大多数相机应用都会为null
提供Data.getData()
值。
其次,即使如果得到Uri
,您也认为Uri
已知MediaStore
。这不是必需的。
第三,即使如果你得到一个Uri
并且 已为MediaStore
所知,你就认为{{1} } column是您可以访问的本地文件的路径。这不是必需的。例如,它可能是可移动存储的路径,您无法在Android 4.4 +上访问。
要解决这三个问题,请使用DATA
指定您希望相机存储图片的位置,并摆脱EXTRA_OUTPUT
以及您对getPath()
的依赖。
第四,在Android 6.0+上使用外部存储时,如果Uri
为23或更高,则需要targetSdkVersion
或READ_EXTERNAL_STORAGE
from the user at runtime。 WRITE_EXTERNAL_STORAGE
权限也是如此。
第五,对于相同的权限,没有CAMERA
和 <uses-permission>
。在您的情况下,请使用<uses-permission-sdk-23>
。