Android实现app分享文件到微信功能
更新时间:2021年5月25日 15:00 点击:2082
本文实例为大家分享了Android实现app分享文件到微信的具体代码,供大家参考,具体内容如下
两种实现方案:
1.使用WXFileObject构造分享方法发送到微信;
2.调用系统分享方法,把文件直接发送到微信;
那么下面来分别看看怎么实现:
0、准备工作
首先,需要在AndroidManifest.xml中配置FileProvider信息,以适配10以后版本文件读取问题
AndroidManifest.xml
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true" tools:replace="android:authorities"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" tools:replace="android:resource" /> </provider>
file_paths.xml
<paths> <external-path name="external_files" path="." /> </paths>
一、使用WXFileObject构造分享方法发送到微信
这种方式分享需要接入微信分享的SDK,分享到微信后可以显示来源。但是官方文档中没有WXFileObject的示例,所以这里贴一段自己写的方法给大家做参考,其他分享类型可以参考官方文档
ShareUtils.java
public static final String PACKAGE_WECHAT = "com.tencent.mm"; /** * 分享文件到微信好友 by WXAPI * * @param thumbId 分享到微信显示的图标 */ public static void shareFileToWechat(Context context, File file, int thumbId) { if (!isInstallApp(context, ShareUtils.PACKAGE_WECHAT)) { Toast.makeText(context, "您需要安装微信客户端", Toast.LENGTH_LONG).show(); return; } //构建发送文件体 WXFileObject fileObject = new WXFileObject(); byte[] fileBytes = readFile(file); //设置需要发送的文件byte[] fileObject.setFileData(fileBytes); fileObject.setFilePath(file.getAbsolutePath()); //使用媒体消息分享 WXMediaMessage msg = new WXMediaMessage(fileObject); //这个title有讲究,最好设置为带后缀的文件名,否则可能分享到微信后无法读取 msg.title = file.getName(); //设置显示的预览图 需小于32KB if (thumbId <= 0) thumbId = R.mipmap.ic_launcher; msg.thumbData = readBitmap(context, thumbId); //发送请求 SendMessageToWX.Req req = new SendMessageToWX.Req(); //创建唯一标识 req.transaction = String.valueOf(System.currentTimeMillis()); req.message = msg; req.scene = SendMessageToWX.Req.WXSceneSession; //WXSceneSession:分享到对话 // 通过WXAPIFactory工厂,获取IWXAPI的实例 IWXAPI api = WXAPIFactory.createWXAPI(context, WXEntryActivity.APP_ID, true); // 将应用的appId注册到微信 api.registerApp(WXEntryActivity.APP_ID); api.sendReq(req); } // 判断是否安装指定app public static boolean isInstallApp(Context context, String app_package) { final PackageManager packageManager = context.getPackageManager(); List<PackageInfo> pInfo = packageManager.getInstalledPackages(0); if (pInfo != null) { for (int i = 0; i < pInfo.size(); i++) { String pn = pInfo.get(i).packageName; if (app_package.equals(pn)) { return true; } } } return false; } /** * 图片读取成byte[] */ private static byte[] readBitmap(Context context, int resourceId) { Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos); return bos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { closeQuietly(bos); } return null; } /** * file文件读取成byte[] */ private static byte[] readFile(File file) { RandomAccessFile rf = null; byte[] data = null; try { rf = new RandomAccessFile(file, "r"); data = new byte[(int) rf.length()]; rf.readFully(data); } catch (Exception exception) { exception.printStackTrace(); } finally { closeQuietly(rf); } return data; } //关闭读取file private static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (Exception exception) { exception.printStackTrace(); } }
效果如下:
二、调用系统分享方法,把文件直接发送到微信
此种方式的好处就是不依赖微信SDK,调用系统提供的分享弹窗来分享到微信。
/** * 直接文件到微信好友 * * @param picFile 文件路径 */ public static void shareWechatFriend(Context mContext, File picFile) { //首先判断是否安装微信 if (isInstallApp(mContext, ShareUtils.PACKAGE_WECHAT)) { Intent intent = new Intent(); intent.setPackage(PACKAGE_WECHAT); intent.setAction(Intent.ACTION_SEND); String type = "*/*"; for (int i = 0; i < MATCH_ARRAY.length; i++) { //判断文件的格式 if (picFile.getAbsolutePath().toString().contains(MATCH_ARRAY[i][0].toString())) { type = MATCH_ARRAY[i][1]; break; } } intent.setType(type); Uri uri = null; if (picFile != null) { //这部分代码主要功能是判断了下文件是否存在,在android版本高过7.0(包括7.0版本) //当前APP是不能直接向外部应用提供file开头的的文件路径, //需要通过FileProvider转换一下。否则在7.0及以上版本手机将直接crash。 try { ApplicationInfo applicationInfo = mContext.getApplicationInfo(); int targetSDK = applicationInfo.targetSdkVersion; if (targetSDK >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { uri = FileProvider.getUriForFile(mContext, mContext.getApplicationContext().getPackageName() + ".fileprovider", picFile); } else { uri = Uri.fromFile(picFile); } intent.putExtra(Intent.EXTRA_STREAM, uri); } catch (Exception e) { e.printStackTrace(); } } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (getVersionCode(mContext, PACKAGE_WECHAT) > VERSION_CODE_FOR_WEI_XIN_VER7) { // 微信7.0及以上版本 intent.setAction(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_STREAM, uri); } mContext.startActivity(Intent.createChooser(intent, "分享文件")); } else { Toast.makeText(mContext, "您需要安装微信客户端", Toast.LENGTH_LONG).show(); } } // 建立一个文件类型与文件后缀名的匹配表 private static final String[][] MATCH_ARRAY = { //{后缀名, 文件类型} {".3gp", "video/3gpp"}, {".apk", "application/vnd.android.package-archive"}, {".asf", "video/x-ms-asf"}, {".avi", "video/x-msvideo"}, {".bin", "application/octet-stream"}, {".bmp", "image/bmp"}, {".c", "text/plain"}, {".class", "application/octet-stream"}, {".conf", "text/plain"}, {".cpp", "text/plain"}, {".doc", "application/msword"}, {".exe", "application/octet-stream"}, {".gif", "image/gif"}, {".gtar", "application/x-gtar"}, {".gz", "application/x-gzip"}, {".h", "text/plain"}, {".htm", "text/html"}, {".html", "text/html"}, {".jar", "application/java-archive"}, {".java", "text/plain"}, {".jpeg", "image/jpeg"}, {".jpg", "image/jpeg"}, {".js", "application/x-javascript"}, {".log", "text/plain"}, {".m3u", "audio/x-mpegurl"}, {".m4a", "audio/mp4a-latm"}, {".m4b", "audio/mp4a-latm"}, {".m4p", "audio/mp4a-latm"}, {".m4u", "video/vnd.mpegurl"}, {".m4v", "video/x-m4v"}, {".mov", "video/quicktime"}, {".mp2", "audio/x-mpeg"}, {".mp3", "audio/x-mpeg"}, {".mp4", "video/mp4"}, {".mpc", "application/vnd.mpohun.certificate"}, {".mpe", "video/mpeg"}, {".mpeg", "video/mpeg"}, {".mpg", "video/mpeg"}, {".mpg4", "video/mp4"}, {".mpga", "audio/mpeg"}, {".msg", "application/vnd.ms-outlook"}, {".ogg", "audio/ogg"}, {".pdf", "application/pdf"}, {".png", "image/png"}, {".pps", "application/vnd.ms-powerpoint"}, {".ppt", "application/vnd.ms-powerpoint"}, {".prop", "text/plain"}, {".rar", "application/x-rar-compressed"}, {".rc", "text/plain"}, {".rmvb", "audio/x-pn-realaudio"}, {".rtf", "application/rtf"}, {".sh", "text/plain"}, {".tar", "application/x-tar"}, {".tgz", "application/x-compressed"}, {".txt", "text/plain"}, {".wav", "audio/x-wav"}, {".wma", "audio/x-ms-wma"}, {".wmv", "audio/x-ms-wmv"}, {".wps", "application/vnd.ms-works"}, {".xml", "text/plain"}, {".z", "application/x-compress"}, {".zip", "application/zip"}, {"", "*/*"} };
效果如下:
以上,就是app通过微信分享文件的2种解决方式。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。
相关文章
- 下面我们来看一篇关于Android子控件超出父控件的范围显示出来方法,希望这篇文章能够帮助到各位朋友,有碰到此问题的朋友可以进来看看哦。 <RelativeLayout xmlns:an...2016-10-02
Android开发中findViewById()函数用法与简化
findViewById方法在android开发中是获取页面控件的值了,有没有发现我们一个页面控件多了会反复研究写findViewById呢,下面我们一起来看它的简化方法。 Android中Fin...2016-09-20- 这篇文章主要介绍了VSCode 配置uni-app的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-11
- 如果我们的项目需要做来电及短信的功能,那么我们就得在Android模拟器开发这些功能,本来就来告诉我们如何在Android模拟器上模拟来电及来短信的功能。 在Android模拟...2016-09-20
- 夜神android模拟器如何设置代理呢?对于这个问题其实操作起来是非常的简单,下面小编来为各位详细介绍夜神android模拟器设置代理的方法,希望例子能够帮助到各位。 app...2016-09-20
- 为了增强android应用的用户体验,我们可以在一些Button按钮上自定义动态的设置一些样式,比如交互时改变字体、颜色、背景图等。 今天来看一个通过重写Button来动态实...2016-09-20
- 如果我们要在Android应用APP中加载html5页面,我们可以使用WebView,本文我们分享两个WebView加载html5页面实例应用。 实例一:WebView加载html5实现炫酷引导页面大多...2016-09-20
- 这篇文章主要介绍了uniapp微信小程序:key失效的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-20
- 深入理解Android中View和ViewGroup从组成架构上看,似乎ViewGroup在View之上,View需要继承ViewGroup,但实际上不是这样的。View是基类,ViewGroup是它的子类。本教程我们深...2016-09-20
- 下面我们来看一篇关于Android自定义WebView网络视频播放控件开发例子,这个文章写得非常的不错下面给各位共享一下吧。 因为业务需要,以下代码均以Youtube网站在线视...2016-10-02
- java开发的Android应用,性能一直是一个大问题,,或许是Java语言本身比较消耗内存。本文我们来谈谈Android 性能优化之MemoryFile文件读写。 Android匿名共享内存对外A...2016-09-20
- TextView默认是横着显示了,今天我们一起来看看Android设置TextView竖着显示如何来实现吧,今天我们就一起来看看操作细节,具体的如下所示。 在开发Android程序的时候,...2016-10-02
android.os.BinderProxy cannot be cast to com解决办法
本文章来给大家介绍关于android.os.BinderProxy cannot be cast to com解决办法,希望此文章对各位有帮助呀。 Android在绑定服务的时候出现java.lang.ClassCastExc...2016-09-20- 这篇文章主要介绍了Android 实现钉钉自动打卡功能的步骤,帮助大家更好的理解和学习使用Android,感兴趣的朋友可以了解下...2021-03-15
- 这篇文章主要介绍了uni-app从安装到卸载的入门教程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-05-15
- 下面我们来看一篇关于Android 开发之布局细节对比:RTL模式 ,希望这篇文章对各位同学会带来帮助,具体的细节如下介绍。 前言 讲真,好久没写博客了,2016都过了一半了,赶紧...2016-10-02
- 这篇文章主要为大家详细介绍了uniapp 实现可以左右滑动导航栏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-10-21
- 首先如果要在程序中使用sdcard进行存储,我们必须要在AndroidManifset.xml文件进行下面的权限设置: 在AndroidManifest.xml中加入访问SDCard的权限如下: <!--...2016-09-20
- 本文主要介绍了手把手教你uniapp和小程序分包,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-02
- 下面来给各位简单的介绍一下关于Android开发之PhoneGap打包及错误解决办法,希望碰到此类问题的同学可进入参考一下哦。 在我安装、配置好PhoneGap项目的所有依赖...2016-09-20