使用原生intent分享图片获取资源失败问题

    xiaoxiao2021-12-10  18

    使用原生intent分享图片获取资源失败问题

    在开发过程中我们经常会遇到分享功能,有很多小伙伴喜欢使用第三方分享框架进行分享,但是偶尔也会用到Intent进行分享,接下来就来说说在使用intent进行分享图片的过程中遇到的那些坑。。

    -首先我们保存一张图片

    private static String saveBitmap(Bitmap bm, String picName) { try { String path = FileConfig.IMG_BASE_FOLDER + picName; File f = new File(path); Log.i("999", "---->path=" + path); if (!f.exists()) { f.getParentFile().mkdirs(); f.createNewFile(); } FileOutputStream out = new FileOutputStream(f); bm.compress(Bitmap.CompressFormat.PNG, 90, out); out.flush(); out.close(); Log.i("999", "保存成功:path=" + path); return f.getAbsolutePath(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; }

    -OK保存成功并获取到了图片的路径,接下来就是对这张图片进行分享了

    String imageUri = saveBitmap("your bitmap","picture name"); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, "一些文字"); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imageUri); shareIntent.setType("image/*"); content.startActivity(Intent.createChooser(shareIntent, "分享的标题)")); or content.startActivity(shareIntent);//这样分享就不带标题了

    -好了这样就可以高高兴兴的去分享啦!但是你以为这样就完成了么?在使用的过程中你会发现,某些应用中会有资源不存在等字样的提示,蒙圈了么?为啥其他的应用可以分享,就你的不行?你特殊些?

    -思考再三,为什么会找不到资源呢?要么就是资源确实不存在(即图片不存在),但是其他应用可以正常分享呀,那么就是在系统中没有找到图片,或者说系统不知道你有这张图片,这样的话,你就得告诉系统,你有一张图片,这样在分享到其他应用的时候,从系统中获取资源的时候获取图片了

    private static String insertImageToSystem(Context context, String imagePath) { String url = ""; try { url = MediaStore.Images.Media.insertImage(context.getContentResolver(), imagePath, SHARE_PIC_NAME, "你对图片的描述"); } catch (FileNotFoundException e) { e.printStackTrace(); } return url; }

    -这样我们在保存图片的时候同时告诉系统,我们有张图片插入到系统图库啦 -代码:

    String imagePath = saveBitmap("your bitmap","picture name"); String imageUri = insertImageToSystem(context, imagePath); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, "一些文字"); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imageUri); shareIntent.setType("image/*"); context.startActivity(Intent.createChooser(shareIntent, "分享的标题)")); or context.startActivity(shareIntent);//这样分享就不带标题了

    -ok这样就大功告成啦

    转载请注明原文地址: https://ju.6miu.com/read-700155.html

    最新回复(0)