Android: action_send put extra_stream from res/drawable folder causes crash

依然范特西╮ 提交于 2019-12-12 01:57:34

问题


I am creating a game, and trying to allow the user to share their win via text/facebook/etc. I am using the code below to grab an image from my res/drawable folder. I am pretty sure I am doing it right, but my app keeps crashing after I choose the send method (ex. facebook). Any help would be greatly appreciated.

Intent ShareIntent = new Intent(android.content.Intent.ACTION_SEND);
ShareIntent.setType("image/jpeg");
Uri winnerPic = Uri.parse("android.resource://com.poop.pals/" + R.drawable.winnerpic);
ShareIntent.putExtra(Intent.EXTRA_STREAM, winnerPic);
startActivity(ShareIntent);

回答1:


Android's resources are only accessible to your app via the resource apis, there is no regular file on the filesystem you can open in other ways.

What you can do is to copy the file from the InputStream you can get to a regular file in a place that is accessible to other apps.

// copy R.drawable.winnerpic to /sdcard/winnerpic.png
File file = new File (Environment.getExternalStorageDirectory(), "winnerpic.png");
FileOutputStream output = null;
InputStream input = null;
try {
    output = new FileOutputStream(file);
    input = context.getResources().openRawResource(R.drawable.winnerpic);

    byte[] buffer = new byte[1024];
    int copied;
    while ((copied = input.read(buffer)) != -1) {
        output.write(buffer, 0, copied);
    }

} catch (FileNotFoundException e) {
    Log.e("OMG", "can't copy", e);
} catch (IOException e) {
    Log.e("OMG", "can't copy", e);
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            // ignore
        }
    }
    if (output != null) {
        try {
            output.close();
        } catch (IOException e) {
            // ignore
        }
    }
}


来源:https://stackoverflow.com/questions/10271993/android-action-send-put-extra-stream-from-res-drawable-folder-causes-crash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!