Android app分享文件到微信

article/2025/10/15 4:58:24

两种实现方案:

1.使用WXFileObject构造分享方法发送到微信;
2.调用系统分享方法,把文件直接发送到微信;

那么下面来分别看看怎么实现:

〇、准备工作

首先,需要在AndroidManifest.xml中配置FileProvider信息,以适配10以后版本文件读取问题

AndroidManifest.xml

		<providerandroid:name="androidx.core.content.FileProvider"android:authorities="${applicationId}.fileprovider"android:exported="false"android:grantUriPermissions="true"tools:replace="android:authorities"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths"tools:replace="android:resource" /></provider>

file_paths.xml

<paths><external-pathname="external_files"path="." />
</paths>

一、使用WXFileObject构造分享方法发送到微信

这种方式分享需要接入微信分享的SDK,分享到微信后可以显示来源。但是官方文档中没有WXFileObject的示例,所以这里贴一段自己写的方法给大家做参考,其他分享类型可以参考官方文档(https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Share_and_Favorites/Android.html )

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;}//ANDROID 11上微信分享得走FileProviderLog.d("share", "SDK_INT=" + Build.VERSION.SDK_INT);if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {shareWechatFriend(context, file);return;}//构建发送文件体WXFileObject fileObject = new WXFileObject();/*经实测,不给fileObject设置fileData,也是可以分享文件得,且大小默认10M以内反而是设置了fileData属性的话,分享文件大小不能大于500kb,且在Android11以上无法分享,坑啊,所以,在Android11上需要走FileProvider文件分享的方式*///设置需要发送的文件byte[] //byte[] fileBytes = readFile(file);//fileObject.setFileData(fileBytes);fileObject.setFilePath(file.getAbsolutePath());fileObject.setContentLengthLimit(1024 * 1024 * 10);//使用媒体消息分享WXMediaMessage msg = new WXMediaMessage(fileObject);//这个title有讲究,最好设置为带后缀的文件名,否则可能分享到微信后无法读取msg.title = file.getName();//设置显示的预览图 需小于32KBif (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);}// 判断是否安装指定apppublic 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;}//关闭读取fileprivate static void closeQuietly(Closeable closeable) {try {if (closeable != null) {closeable.close();}} catch (Exception exception) {exception.printStackTrace();}}

效果如下:
分享文件
PS:
经实测,不给fileObject设置fileData,也是可以分享文件得,且大小默认10M以内。反而是设置了fileData属性的话,分享文件大小不能大于500kb,且在Android11以上无法分享,坑啊,所以,在Android11上需要走FileProvider文件分享的方式。

二、调用系统分享方法,把文件直接发送到微信

此种方式的好处就是不依赖微信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种解决方式。


http://chatgpt.dhexx.cn/article/13U6m6Jv.shtml

相关文章

ShareSDK关于微信分享问题

转自&#xff1a;http://www.eoeandroid.com/thread-310281-1-1.html 发现用sharesdk&#xff0c;做其他平台分享很快&#xff1b;如新浪微博、腾讯微博、有道云笔记、开心网、Google等等&#xff0c;几句代码就搞定&#xff1b; 但是微信有点麻烦&#xff0c;下面我把…

uniapp实现录音喊话功能

直接先上代码&#xff1a; const recorderManager uni.getRecorderManager() onShow() {this.test()},methods: {test() {uni.getSetting({success: (res) > {console.log(res.authSetting, res.authSetting[scope.record]);if (res.authSetting[scope.record] false) {…

h5调用android录音,html5网页录音插件Recorder

插件描述&#xff1a;html5 js 录音 mp3 wav ogg webm amr 格式&#xff0c;支持pc和Android、ios部分浏览器、和Hybrid App(提供Android IOS App源码)&#xff0c;微信也是支持的&#xff0c;提供H5版语音通话聊天示例 Recorder用于html5录音 支持大部分已实现getUserMedia的移…

利用RecordRTC.js实现H5录音功能

前言&#xff1a; 最近遇到 要语音转文字 的需求&#xff0c;语音转文字肯定要先搞定录音功能&#xff0c;在网上找了好久没找到具体的 RecordRTC.js 插件的使用方法&#xff0c;最后只能对着 github 上开源代码小试了一下&#xff0c;录音功能好使所以就记录一下叭 一、Reco…

vue录音+js-audio-recorder

小小记录一下项目中用到的录音功能 1.下载插件 npm i js-audio-recorder 2.展示代码 <template><div style"padding: 20px;"><div style"font-size:14px"><h3>录音时长&#xff1a;{{ recorder && recorder.duration.…

html 苹果微信录音js,微信js-sdk 录音功能的示例代码

需求描述 制作一个H5页面&#xff0c;打开之后可以录音&#xff0c;并将录音文件提交至后台 微信录音最长时长为1min 代码如下 // isVoice&#xff1a; 0-未录音 1-录音中 2-录完音 // 点击录音/录音中 按钮展示 点击录音 // isListen // 0-未试听/试听结束 1-试听中 2-暂停试听…

已解决:H5移动端网页实现录音功能,js实现录音功能,包括安卓webview接口也可以使用

遇到一个需求&#xff0c;需要做一个手机网页录音的功能&#xff0c;嵌入到webview中去&#xff0c;用安卓原生录音倒是可以&#xff0c;但是想着尽量去安卓化开发&#xff0c;就想着用纯的js前端代码去实现录音功能。 在 Web 应用程序中&#xff0c;JavaScript 是运行在浏览器…

网页录音时的麦克风权限问题解决

来源 | https://www.html.cn/web/html/19184.html 在我们进行网页制作时可能会遇到需要录音的情况&#xff0c;而在进行网页录音时又有可能会遇到麦克风权限问题导致无法录音&#xff0c;本文就来为大家介绍一下如何解决麦克风权限问题。 在本地中打开的时候&#xff0c;谷歌、…

获取摄像头和麦克风权限_js获取浏览器摄像头和麦克风权限

前言 项目中会使用到摄像头或麦克风设备&#xff0c;这就需要我们获取浏览器的摄像头和麦克风权限&#xff0c;权限是无法通过js操控的&#xff0c;必须由浏览器用户设置。 下面我来告诉大家如何获取浏览器的摄像头或麦克风的权限&#xff0c;使浏览器弹出询问窗口。 一、我们想…

(前端)录音功能实现 js-audio-recorder

1. 创建 import Recorder from js-audio-recorder const parameter {sampleBits: 16, // 采样位数&#xff0c;支持 8 或 16&#xff0c;默认是16sampleRate: 8000, // 采样率&#xff0c;支持 11025、16000、22050、24000、44100、48000&#xff0c;根据浏览器默认值&#x…

Android webview录音权限和音频自动播放

项目背景&#xff1a;我们通过layabox&#xff0c;制作了H5页面&#xff0c;可以在微信中&#xff0c;手机浏览器中使用&#xff0c;现在需要将H5页面集成到Android的APP中。 遇到的问题&#xff1a; 1.遇到的第一个问题&#xff0c;是获取录音权限的问题&#xff0c;我已经给…

html 苹果微信录音js,基于JS开发微信网页录音功能的实例代码

具体代码如下所示&#xff1a; wx.ready(function () { var startRecordflag false var startTime null //btnRecord 为录音按钮dom对象 btnRecord.addEventListener(touchstart, function (event) { event.preventDefault(); startTime newDate().getTime(); // 延时后录音…

std::string 与 std::wstring 互转

前言: 最近接触了一些 win32 方便的编程,由于不熟 可能会写一写这方便的基础东西 相当于 写日记了 提升一下 他们的声明 string 是 char wstring 是wchar_t 什么是wchar_t ? string 转 wstring inline std::wstring StringToWString(const std::string& str) {int len…

C++ 字符串string、字符char、宽字符数组wstring、宽字符wchar_t互相转换(2021.4.20)

C单字符串和宽字符串学习 2021.4.20 1、char 和 string1.1 单字符 char1.2 单字符数组 char[] 和 char*1.2.1 char[]1.2.2 char* 1.3 单字符串 string1.4 char[] 转 string1.5 cha[] 转char*1.6 string 转 char*1.7 string 转 char[] 2、wchar_t 和 wstring2.1 宽字符 wchar_t2…

string和wstring相互转换以及wstring显示中文问题

如果你只是使用C来处理字符串&#xff0c;会用到string。不过string是窄字符串ASCII&#xff0c;而很多Windows API函数用的是宽字符Unicode。这样让string难以应对。作为中国的程序员&#xff0c;我们第一个想到的字符串就是中文&#xff0c;而不是英文。所以经常会遇到中文字…

C++里面,什么时候使用std::wstring

看你要使用什么字符编码了&#xff0c; std::wstring主要用于 UTF-16编码的字符,而std::string主要用于存储单字节的字符( ASCII字符集 )&#xff0c;但是也可以用来保存UTF-8编码的字符。&#xff08;UTF-8和UTF-16是UNICODE字符集的两种不同的字符编码&#xff09; 如果你的…

String类与wstring类的区别

String类与wstring类的区别 本质区别 存储字符的区别 #include <iostream> #include <string> using namespace std; int main() { wstring wstr1 L"你好世界"; // L普通字符串 宽字符串 const wchar_t *ch1 wstr1.c_str(); // 转化为宽字符…

从新建工程开始使用C++开发单片机(以STM32为例):七、移植Arduino的WString(附代码)

在上一篇文章中&#xff0c;介绍了outputString和inputString&#xff0c;其中所运用到的字符串类型String也是C驱动层中功能强大且重要的一个类。这个类移植自Arduino的WString。这篇文章将会展示WString的易用性&#xff0c;并且从编译输出后程序大小的角度比较WSting和C std…

0005:Qt常用类 - QDateTime

Qt常用类 - QDateTime 1 开发环境 在介绍内容之前&#xff0c;先说明一下开发环境&#xff0c;如下图&#xff1a; Qt版本&#xff1a;Qt5.3.2&#xff1b; Qt开发工具&#xff1a;Qt Creater 3.2.1&#xff1b; Qt构建工具&#xff1a;Desktop Qt 5.3 MinGW 32bit&#xff…

QDateTime的11种显示方式

QDateTime datetime QDateTime::currentDateTime(); datetime.toString(“hh:mm:ss\nyyyy/MM/dd”); datetime.toString(“hh:mm:ss ap\nyyyy/MM/dd”); datetime.toString(“hh:mm:ss\nyyyy-MM-dd”); datetime.toString(“hh:mm:ss ap\nyyyy-MM-dd”); datetime.to…