简体   繁体   中英

Whatsapp crashes when trying to share Image through ShareAction Provider

So, I first take the image from the drawable folder and then try to share the same through ShareActionProvider but Whatsapp (or any other app) keeps on crashing. It successfully sends the text but not an image. The image is in PNG format.

This is my Menu XML Layout:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.android.shareactivity.ShareActivity">

<item
    android:title="share"
    android:id="@+id/action_share"
    android:orderInCategory="2"
    app:showAsAction="always"
    app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
    />
</menu>

This is my implementation of ShareActionProvider

public class Sharing extends AppCompatActivity {

    private ShareActionProvider mShareActionProvider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sharing);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        //Share Action Provider
        MenuItem menuItem = menu.findItem(R.id.action_share);
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);

        if(mShareActionProvider!=null) {

            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            sharingIntent.setType("image/*");
            sharingIntent.putExtra(Intent.EXTRA_STREAM, R.drawable.untitled);

            // sharingIntent.setType("text/*");
            // sharingIntent.putExtra(Intent.EXTRA_TEXT,"Hello World");
            mShareActionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
            mShareActionProvider.setShareIntent(sharingIntent);
        }

        return true; 
    }
}

The problem lies in this line

sharingIntent.putExtra(Intent.EXTRA_STREAM, R.drawable.untitled);

You cannot pass a drawable which is inside your package to any other app, you will have to write this as png or jpg on the disk and then share the path of that file to whatsapp.

If your targetSdkVersion is 24 or above you will have to use file provider to share your file with any other app

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM