Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android app分享文件到微信

Android实现app分享文件到微信功能

作者:椰子z

这篇文章主要为大家详细介绍了Android实现app分享文件到微信功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了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种解决方式。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文