第三方分享我就不多说了,都有官方文档。最近项目遇到多图分享功能,发现第三方都不能满足这个功能。要想实现这个功能只能使用自己手机系统自带的分享。每个手机有所不同。首先说下简单调出系统分享功能的方法,主要是用intent功能来打开第三方程序。
代码如下:
Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT,"This is my text to send."); sendIntent.setType("text/plain"); startActivity(Intent.createChooser(sendIntent,"分享"));
第二步根据我们的需求来定制我们分享的文件类型
sendIntent.setType("text/plain");
sendIntent.setType("image/*");图片分享包含多个图片和单个图片分享:直接说多个因为多个也包括单个。
具体代码如下(一种是本地图片,另一种是从后台获取之后保存到本地之后的图片)
在上述代码中添加如下代码
ArrayList<Uri> imageUris = new ArrayList<>(); for (int i=0;i<files.size();i++){ if(Build.VERSION.SDK_INT>=24) { //判读版本是否在7.0以上 Uri uri = null; try { uri = Uri.parse(android.provider.MediaStore.Images.Media. insertImage(context.getContentResolver(), ((File) files.get(i)).getAbsolutePath(), ".jpg", null)); } catch (FileNotFoundException e) { e.printStackTrace(); } imageUris.add(uri); }else{ imageUris.add(Uri.fromFile((File) files.get(i)));//仅支持7.0以下版本 } }这里面的files是我的图片文件集合 因为是从后台获取的所以我先保存到本地再进行分享 保存方法如下:
for (int i=0;i<mapList.size();i++){ if (mapList.get(i).get("isChose").equals("1")){ ImageView image = (ImageView) gridView.getChildAt(i).findViewById(R.id.image1); BitmapDrawable drawable = (BitmapDrawable) image.getDrawable(); if (drawable != null) { Bitmap bmp = drawable.getBitmap(); if (bmp != null) { saveBitmap(bmp,mapList.get(i).get("image")); } } } }上面使做的多选功能,从空间imageview中获取到图片保存到本地 然后把文件加入到files集合中
//设置保存路径 public static File createStableImageFile(Context context, int IMAGE_NAME) throws IOException { String imageFileName =Integer.toString(IMAGE_NAME) + ".jpg"; File dir = context.getExternalFilesDir(null); if (dir == null || dir.getAbsolutePath().equals("")) { dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()); } return new File(dir, imageFileName); }
//方法里注释掉的保存路径用上面的保存路径代替
// 保存图片到内存卡 保存多张图片到本地 private void saveBitmap(Bitmap bitmap, String url) { //File file = new File(Environment.getExternalStorageDirectory()+"//DCIM//2298//", // MyUtils.MD5(url)+".png"); // files.add(file); File dir = new File(file.getParent()); if(!dir.exists()) dir.mkdirs(); //没有目录就创建 if (file.exists()) file.delete(); //文件存在就删除 try { FileOutputStream out = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 90, out); out.flush(); out.close(); Toast.makeText(this, "图片保存到:"+dir, Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "图片保存异常:"+e.getMessage(), Toast.LENGTH_LONG).show(); } }
//关于实现自己的布局分享到单个程序,我这里在网上查到微信 微信朋友圈 扣扣等
ComponentName comp = null;//选择要启动的程序 switch (flag){ case 1://微信 comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI"); break; case 2://朋友圈 comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI"); break; case 3://扣扣 comp = new ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity"); break; } intent.setComponent(comp);//启动另外一个程序