Android: How to use grantUriPermission to be able to create and send an email with a bitmap attachment

后端 未结 3 1094
心在旅途
心在旅途 2021-01-04 12:18

From within my application, I\'m trying to create an email that contains an image contained in a bitmap object.

private void sendEmailWithBitmapAttached(){ 
         


        
3条回答
  •  无人及你
    2021-01-04 12:42

    I had a similar issue. Below is how I solved the problem for my project. You should be able to adapt this for your solution. This solution also has some Firebase code, which you can ignore. The key points are ActivityCompat.requestPermissions and ActivityCompat.checkSelfPermission:

    private void shareViaEmail() {
        int permissionCheck = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                LayoutInflater inflater = this.getLayoutInflater();
                final ViewGroup nullParent = null;
                final View dialogView = inflater.inflate(R.layout.alert_dialog, nullParent);
                alertBuilder.setView(dialogView);
    
                alertBuilder.setCancelable(true);
                alertBuilder.setTitle("Permission request");
    
                String message = "\n\n" + getString(R.string.email_images);
                AppCompatTextView notice = (AppCompatTextView) dialogView.findViewById(R.id.notice);
                if (notice != null) {
                    notice.setText(message);
                    notice.setTextSize(getResources().getInteger(R.integer.dialog_text_size));
                }
                else {
                    alertBuilder.setMessage(message);
                }
    
                alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
    
                    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                    public void onClick(DialogInterface dialog, int which) {
                        mShowingAlert = false;
                        ActivityCompat.requestPermissions(baseActivity(), new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_TARGET_WRITE_PERMISSION_REQUEST);
                    }
                });
    
                mAlertDialog = alertBuilder.create();
                mAlertDialog.show();
                return;
            }
        }
        ActivityCompat.requestPermissions(this,
                new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                MY_TARGET_WRITE_PERMISSION_REQUEST);
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            if (requestCode == MY_TARGET_WRITE_PERMISSION_REQUEST) {
                doShareViaEmail();
            } else {
                failWriteImage();
            }
        }
    }
    
    protected void failWriteImage() {
        getHandler().post(new Runnable() {
            @Override
    
            public void run() {
                String email_failed = getResources().getString(R.string.fail_email_attach);
                @SuppressLint("ShowToast") Toast toast = Toast.makeText(getApplicationContext(), email_failed, Toast.LENGTH_SHORT);
                new CustomToast(toast).invoke();
            }
        });
    }
    
    protected void doShareViaEmail() {
        FireUtilities fireUtilities = FireUtilities.getInstance();
        fireUtilities.logEvent(mFirebaseAnalytics, "option_item", "share", "share_string");
    
        Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.string_share));
    
        String appStoreLink = getString(R.string.app_store_link);
    
        String emailText = getString(R.string.share_string_body1)
                + " " + appStoreLink
                + " " + getString(R.string.share_string_body2);
    
        emailText = emailText + "

    " + getTitleOfSegment(true, mCurrentSegment, mCurrentSegmentIndex); Bitmap targetImage = screenShot(mTargetImageView); if (targetImage != null) { ArrayList files = new ArrayList(); String path = MediaStore.Images.Media.insertImage(getContentResolver(), targetImage, "string", null); Uri targetUri = Uri.parse(path); files.add(targetUri); intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files); } intent.setType("message/rfc822"); Spanned htmlText = fromHtml(getString(R.string.share_score_head1) + emailText + getString(R.string.share_score_head2)); intent.putExtra(Intent.EXTRA_TEXT, htmlText); try { startActivityForResult(Intent.createChooser(intent, "Email:"), 1234); } catch (final android.content.ActivityNotFoundException e) { String no_email_client = getResources().getString(R.string.no_email_client); @SuppressLint("ShowToast") Toast toast = Toast.makeText(getApplicationContext(), no_email_client, Toast.LENGTH_LONG); new CustomToast(toast).invoke(); } } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1234) { LogHelper.v(TAG, "e-mail successfully sent"); } } public Bitmap screenShot(View view) { if (view != null) { Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); view.draw(canvas); return bitmap; } return null; }

提交回复
热议问题