Android调用系统分享,资源未找到问题
16lz
2021-01-23
Android调用系统的分享来分享网络图片,是不能直接分享网络图片的,需要把图片保存到本地:
// 保存图片public static void saveBitmap(Bitmap bitmap, String filePath, String fileName) { File headDir = new File(filePath); if (!headDir.exists()) { headDir.mkdirs(); } FileOutputStream headFos = null; File headFile = null; try { //重命名并保存 headFile = new File(filePath, fileName); headFile.createNewFile(); headFos = new FileOutputStream(headFile); bitmap.compress(CompressFormat.JPEG, 100, headFos); headFos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (headFos != null) { try { headFos.close(); } catch (IOException e) { e.printStackTrace(); } } } }// 网络图片转成bigmap对象public static Bitmap getBitMBitmap(String urlpath) { Bitmap map = null; try { URL url = new URL(urlpath); URLConnection conn = url.openConnection(); conn.connect(); InputStream in; in = conn.getInputStream(); map = BitmapFactory.decodeStream(in); } catch (IOException e) { e.printStackTrace(); } return map; }
// 调用系统分享public void share(String imgUrl) {String imgPath = "自已定义路径";String imgName = "share.jpg";saveBitmap(getBitMBitmap(imgUrl), imgPath, imgName);Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/*"); intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imgPath + "/" + imgPath )); startActivity(Intent.createChooser(intent, "图片描述,随便写"));}
但是这时候我们去分享是不行的,我开始这样去分享只有QQ好友成功了,其他的都没成功,因为你只是把图片存到本地了,而你调系统的分享,系统不知道你给它保存了这个图片,所以它去分享的时候它会说我不知道有这张图片,可不就是资源未找到,所以我们要告诉系统 我给你保存了一张图片:
/** * 这个参数是你保存到本地图片的绝对路径(包括文件名.jpg的) */public static String insertImageToSystem(Context context, String imagePath) { String url = ""; try { url = MediaStore.Images.Media.insertImage(context.getContentResolver(), imagePath, imgName , "分享"); } catch (FileNotFoundException e) { e.printStackTrace(); } return url; }
最终调用系统分享:
// 调用系统分享public void share(String imgUrl) {String imgPath = "自已定义路径";String imgName = "share.jpg";saveBitmap(getBitMBitmap(imgUrl), imgPath, imgName);insertImageToSystem(context, imgAbsPath);// imgAbsPath:图片绝对路径Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/*"); intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imgPath + "/" + imgPath )); startActivity(Intent.createChooser(intent, "图片描述,随便写"));}
更多相关文章
- Android下使用Socket连接网络电脑
- android系统权限关机重启
- Android模拟、实现、触发系统按键事件的方法
- android 日期时间格式转换;软键盘显示消失;获取系统title
- C# mono android 图片上传进度条实现
- 网络书签about Android
- Android内核的根文件系统
- Android P 系统应用无法对外置SD卡进行读写