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種解決方式。

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: