androidandroid-intentshare-intent

Android (share button) crash in startActivity for Intent.createChooser works with most of phones except pixel


I'm doing app to share a png image to facebook and all, the code works fine in my Huawei Honor 8 and crashes with the google pixel 2. code:

showLoading("Saving...");
File f = new File(Environment.getExternalStorageDirectory()
                + File.separator + ""
                + System.currentTimeMillis() + ".png");
photoEditorView.getSource().setImageURI(Uri.fromFile(f));
Uri contentUri = Uri.fromFile(f);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "title");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
share.putExtra(Intent.EXTRA_STREAM, contentUri);
startActivity(Intent.createChooser(share, "Share Image!"));

Solution

  • Try this code,

    File nFile = new File(selectedImagePath);
                        Uri mmuri;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            mmuri = getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider",nFile);
                        } else{
                            mmuri = Uri.fromFile(nFile);
                        }
    

    using mmuri uri for sending image.

    add in manifest

    <provider
                    android:name="android.support.v4.content.FileProvider"
                    android:authorities="your package name.provider"
                    android:exported="false"
                    android:grantUriPermissions="true">
                    <meta-data
                        android:name="android.support.FILE_PROVIDER_PATHS"
                        android:resource="@xml/provider_paths" />
                </provider>
    

    in res make xml folder and create provider_paths.xml file and add below code.

    <?xml version="1.0" encoding="utf-8"?>
    <paths>
        <external-path
            name="external_files"
            path="." />
        <root-path
            name="external_files"
            path="/storage/" />
    </paths>