微信开放文档没有关于分享文件的介绍,在网上收到了解决方案如下:
fun shareFileToWechat(filePath: String, title: String, type: String = "file"): Boolean {
val api = WXAPIFactory.createWXAPI(
getContext(),
wxKey,
true
)
if (api.isWXAppInstalled) {
api.registerApp(wxKey)
val fileObj = WXFileObject()
fileObj.fileData = WXUtil.inputStreamToByte(filePath)
fileObj.filePath = filePath
//使用媒体消息分享
val msg = WXMediaMessage()
msg.mediaObject = fileObj
msg.title = title
//发送请求
val req = Req()
//创建唯一标识
req.transaction = buildTransaction(trim(type))
req.message = msg
req.scene = Req.WXSceneSession
api.sendReq(req)
return true
} else {
ToastUtil.toast(string.uninstall_wechat)
return false
}
}
这种方案是将文件的路径和文件的字节数组都传递给微信,文件大小超过1MB,文件分享页面跳转失败。
public void serialize(Bundle var1) {
var1.putByteArray("_wxfileobject_fileData", this.fileData);
var1.putString("_wxfileobject_filePath", this.filePath);
}
文件的路径和文件的字节数组是通过Bundle传递的,Bundle最大支持传递1MB的数据,所以跳转失败,解决方案是删除fileObj.fileData = WXUtil.inputStreamToByte(filePath)这行代码,最终代码如下:
fun shareFileToWechat(filePath: String, title: String, type: String = "file"): Boolean {
val api = WXAPIFactory.createWXAPI(
getContext(),
wxKey,
true
)
if (api.isWXAppInstalled) {
api.registerApp(wxKey)
val fileObj = WXFileObject()
fileObj.filePath = filePath
//使用媒体消息分享
val msg = WXMediaMessage()
msg.mediaObject = fileObj
msg.title = title
//发送请求
val req = Req()
//创建唯一标识
req.transaction = buildTransaction(trim(type))
req.message = msg
req.scene = Req.WXSceneSession
api.sendReq(req)
return true
} else {
ToastUtil.toast(string.uninstall_wechat)
return false
}
}
但第二种方案也无法分享10MB以上的文件,因为微信平台做了限制,会对文件的大小进行合法检验。
private int contentLengthLimit = 10485760;
public boolean checkArgs() {
if (this.fileData != null && this.fileData.length != 0 || this.filePath != null && this.filePath.length() != 0) {
if (this.fileData != null && this.fileData.length > this.contentLengthLimit) {
Log.e("MicroMsg.SDK.WXFileObject", "checkArgs fail, fileData is too large");
return false;
} else if (this.filePath != null && this.getFileSize(this.filePath) > this.contentLengthLimit) {
Log.e("MicroMsg.SDK.WXFileObject", "checkArgs fail, fileSize is too large");
return false;
} else {
return true;
}
} else {
Log.e("MicroMsg.SDK.WXFileObject", "checkArgs fail, both arguments is null");
return false;
}
}