/** * 单文件分享 */ private void shareSingleFile() { Uri uri = Uri.fromFile(new File(“文件路径”)); Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, uri); shareIntent.setType("*/*"); startActivity(Intent.createChooser(shareIntent, "分享到")); }
/** * 多文件分享,仅限图片 */ private void shareMultipleFile() { ArrayList<Uri> myList = new ArrayList<Uri>(); for (int i = 0; i < 10; i++) { myList.add(Uri.fromFile(new File(“文件路径”))); } Intent shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE); shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, myList); shareIntent.setType("image/*"); startActivity(Intent.createChooser(shareIntent, "分享到")); }
通过上面的代码跳转会弹出Android默认的分享接口选项给用户选择。
若是你只想使用其中的一种或者几种分享,则可以通过以下代码进行过滤:
PackageManager localPackageManager = getPackageManager(); HashMap<String, ActivityInfo> localHashMap = new HashMap<String, ActivityInfo>(); try { //根据intent来查找本地apk适合的分享接口列表。 List<ResolveInfo> localList = localPackageManager.queryIntentActivities( shareIntent, 0); Iterator<ResolveInfo> localIterator = localList.iterator(); while (localIterator.hasNext()) { //遍历分享接口。 ResolveInfo resolveInfo = (ResolveInfo) localIterator.next(); ActivityInfo localActivityInfo = resolveInfo.activityInfo; String str = localActivityInfo.name; //过滤接口,如只需用到微信分享。如不知道string,可进行调试,通过localList列表中查看。 if (str.contains("com.tencent.mm.ui.tools.ShareImgUI")) localHashMap.put(str, localActivityInfo); } } catch (Exception localException) { L.d("exception" + localException); } ActivityInfo localActivityInfo = (ActivityInfo) localHashMap.get("com.tencent.mm.ui.tools.ShareImgUI"); if (localActivityInfo == null) { ToastMessage("微信分享异常,请检查客户端再试!", Toast.LENGTH_SHORT); return; } if (localActivityInfo != null) { //根据过滤下来的接口进行跳转,也可自定义选项框进行选择跳转。 shareIntent.setComponent(new ComponentName(localActivityInfo.packageName, localActivityInfo.name)); startActivityForResult(shareIntent, 0); }}