无法从Android 8和9的相机和图库上传图像

时间:2019-05-15 06:27:16

标签: android android-camera android-gallery android-camera-intent

我的应用程序中有个人资料图片概念。用户可以选择从应用程序中的相机或图库上载图像,但问题是图像正在上载到某些设备,而不是全部。问题主要出在Android 8和9版本上。我几乎尝试了所有方法,但未能实现。请帮忙。

代码:

   dialog = new Dialog(getActivity());
            dialog.setContentView(R.layout.dialog_image_upload);
            dialog.setCanceledOnTouchOutside(false);
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

            TextView txtTakePhoto = (TextView) dialog.findViewById(R.id.txtTakePhoto);
            TextView txtPictureFromGallery = (TextView) dialog.findViewById(R.id.txtPictureFromGallery);
            ImageView imgClose = (ImageView) dialog.findViewById(R.id.imgClose);

            imgClose.setOnClickListener(this);
            txtTakePhoto.setOnClickListener(this);
            txtPictureFromGallery.setOnClickListener(this)

从相机拍摄照片的代码:

        case R.id.txtTakePhoto:

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    {
                        cameraIntent();
                    }

                } else {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
                        Toast.makeText(getActivity(), "App requires Phone permission.\nPlease allow that in the device settings.", Toast.LENGTH_LONG).show();
                    }
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, PHONE_PERMISSION_CODE);
                }
            } else {
                cameraIntent();

            }
            break;

从画廊拍照的代码:

        case R.id.txtPictureFromGallery:

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    {
                        imageBrowse();

                    }

                } else {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
                        Toast.makeText(getActivity(), "App requires Phone permission.\nPlease allow that in the device settings.", Toast.LENGTH_LONG).show();
                    }
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PHONE_PERMISSION_CODE);
                }
            } else {

                imageBrowse();

            }
            break;

待上传图片的代码:

        private void cameraIntent() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQUEST_CAMERA);

}


private void imageBrowse() {

    Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}


//handling the image chooser activity result
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == PICK_IMAGE_REQUEST) {

            onSelectFromGalleryResult(data);

        } else if (requestCode == REQUEST_CAMERA) {

            onCaptureImageResult(data);
        }
    }
     //
        if (requestCode == 2 && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri DbsUri = data.getData();
        fileDbs = FilePath.getPath(getActivity(), DbsUri);
        File f1 = new File(fileDbs);
        edtCertificatesValue.setText(f1.getName());

        Log.e("tag", "filedbs" + fileDbs);

    } else if (requestCode == 3 && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri picUri = data.getData();
        filePath = FilePath.getPath(getActivity(), picUri);
        File f2 = new File(filePath);
        edtIdentityDocumentValue.setText(f2.getName());
        Log.e("tag", "filePath" + filePath + " " + f2.getName());


    } else if (requestCode == 4 && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri picUri = data.getData();
        fileAddress = FilePath.getPath(getActivity(), picUri);
        File f3 = new File(fileAddress);
        edtProofOfAddressValue.setText(f3.getName());
        Log.e("tag", "fileAddress" + fileAddress);

    } else if (requestCode == 5 && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri CvUri = data.getData();
        fileCvPath = FilePath.getPath(getActivity(), CvUri);
        File f4 = new File(fileCvPath);
        edtCurriculumVitaeValue.setText(f4.getName());
        Log.e("tag", "fileCvPath" + fileCvPath);
//
    }
 //
 //        } else
  }

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
    bm = null;


    File imageFile = getTempFile(getActivity());
    if (data != null) {
        try {
            bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    boolean isCamera = (data == null ||
            data.getData() == null ||
            data.getData().toString().contains(imageFile.toString()));

    if (isCamera) { /* CAMERA */
        selectedImageUri = Uri.fromFile(imageFile);
    } else { /* ALBUM */
        selectedImageUri = data.getData();
    }

    bm = getImageResized(getActivity(), selectedImageUri);
    int rotation = getRotation(getActivity(), selectedImageUri, isCamera);
    bm = rotate(bm, rotation);

    ByteArrayOutputStream bytes1 = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 99, bytes1);

    byte[] byteImage = bytes1.toByteArray();
    encodeImage = Base64.encodeToString(byteImage, Base64.DEFAULT);


    imgProfile.setImageBitmap(bm);

    Uri picUri = data.getData();

    Log.e("TAG", "onSelectFromGalleryResult: " + bm);


    fileImagePath = getPath(picUri);

    if (fileImagePath != null) {

        try {

        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {

        Toast.makeText(getActivity(), R.string.some_error_occured, Toast.LENGTH_LONG).show();
    }

    dialog.dismiss();

}

private String getPath(Uri contentUri) {
    String[] proj = {MediaStore.Images.Media.DATA};
    CursorLoader loader = new CursorLoader(getActivity(), contentUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String result = cursor.getString(column_index);
    cursor.close();
    return result;
}

//新代码

private static File getTempFile(Context context) {
    File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
    imageFile.getParentFile().mkdirs();
    return imageFile;
}



 private void onCaptureImageResult(Intent data) {

    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes1 = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 99, bytes1);
    byte[] byteImage = bytes1.toByteArray();
    encodeImage = Base64.encodeToString(byteImage, Base64.DEFAULT);


    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");

    Log.d("TAG", "onActivityResult: " + Uri.fromFile(destination));
    try {
        rotateImageIfRequired(thumbnail, getActivity(), Uri.fromFile(destination));
    } catch (Exception e) {
        e.printStackTrace();
    }

    Log.d("TAG", "thumbnail: " + thumbnail);

    imgProfile.setImageBitmap(thumbnail);

    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes1.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


    fileImagePath = destination.toString();

    if (fileImagePath != null) {

        try {
              // execMultipartPost();
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        Toast.makeText(getActivity(), getResources().getString(R.string.some_error_occured), Toast.LENGTH_LONG).show();
    }

    dialog.dismiss();
}



 //This method will be called when the user will tap on allow or deny
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    //Checking the request code of our request
    if (requestCode == STORAGE_PERMISSION_CODE) {

        //If permission is granted
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //Displaying a toast
            Toast.makeText(getActivity(), "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
        } else {
            //Displaying another toast if permission is not granted
            Toast.makeText(getActivity(), "Oops you just denied the permission", Toast.LENGTH_LONG).show();
        }
    }
}

API匹配代码:

  private void execMultipartPost() throws Exception {

    RequestBody requestBody;

    pBar.setVisibility(View.VISIBLE);


    final HashMap<String, String> loggedDetail = sessionManager.getLoggedDetail();
    HashMap<String, String> params = new HashMap<String, String>();

    String api_token = loggedDetail.get("api_token");

    if (filePath != null) {
        File file = new File(filePath);
        String contentType = file.toURL().openConnection().getContentType();
        fileBody = RequestBody.create(MediaType.parse(contentType), file);
        filename = "file_" + System.currentTimeMillis() / 1000L;

        Log.e("TAG", "filename: " + filename);

        requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image_file", filename + ".jpg", fileBody)
                .addFormDataPart("name", edtName.getText().toString())
                .addFormDataPart("user_id", loggedDetail.get("id"))
                .addFormDataPart("email", edtEmailValue.getText().toString())

                .addFormDataPart("postal_code", edtPostCodeValue.getText().toString())
                .addFormDataPart("phone", edtPhoneNumber.getText().toString())
                .addFormDataPart("type", loggedDetail.get("type"))
                .addFormDataPart("address", edtAddressValue.getText().toString())
                .addFormDataPart("gender", edtGenderValue.getText().toString())
                .addFormDataPart("skype_id", edtSkypeNameIdValue.getText().toString())


                .build();

    } else {

        requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image_file", "")
                .addFormDataPart("name", edtName.getText().toString())
                .addFormDataPart("user_id", loggedDetail.get("id"))
                .addFormDataPart("email", edtEmailValue.getText().toString())

                .addFormDataPart("postal_code", edtPostCodeValue.getText().toString())
                .addFormDataPart("phone", edtPhoneNumber.getText().toString())
                .addFormDataPart("type", loggedDetail.get("type"))
                .addFormDataPart("address", edtAddressValue.getText().toString())
                .addFormDataPart("gender", edtGenderValue.getText().toString())
                .addFormDataPart("skype_id", edtSkypeNameIdValue.getText().toString())

                .build();
    }


    okhttp3.Request request = new okhttp3.Request.Builder()
            .url(Constants.EDIT_PROFILE_DATA)
            .post(requestBody)
            .addHeader("Authorization", "Bearer " + loggedDetail.get("api_token"))
            .build();


    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(150, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();


    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, final IOException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    pBar.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), R.string.some_error_occured, Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            });
        }


        @Override
        public void onResponse(Call call, final okhttp3.Response response) throws IOException {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

1 个答案:

答案 0 :(得分:0)

是的,您需要配置FileProvider。在您的应用清单中,将提供程序添加到您的应用中:

<application>
   ...
   <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.android.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
    </provider>
    ...
</application>

确保授权字符串与getUriForFile(Context,String,File)的第二个参数匹配。在提供程序定义的元数据部分中,您可以看到提供程序希望在专用资源文件res / xml / file_paths.xml中配置合格的路径。这是此特定示例所需的内容:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>

阅读android文档https://developer.android.com/training/camera/photobasics