Android實(shí)現(xiàn)app分享文件到微信功能
本文實(shí)例為大家分享了Android實(shí)現(xiàn)app分享文件到微信的具體代碼,供大家參考,具體內(nèi)容如下
兩種實(shí)現(xiàn)方案:
1.使用WXFileObject構(gòu)造分享方法發(fā)送到微信;
2.調(diào)用系統(tǒng)分享方法,把文件直接發(fā)送到微信;
那么下面來(lái)分別看看怎么實(shí)現(xiàn):
0、準(zhǔn)備工作
首先,需要在AndroidManifest.xml中配置FileProvider信息,以適配10以后版本文件讀取問(wèn)題
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構(gòu)造分享方法發(fā)送到微信
這種方式分享需要接入微信分享的SDK,分享到微信后可以顯示來(lái)源。但是官方文檔中沒有WXFileObject的示例,所以這里貼一段自己寫的方法給大家做參考,其他分享類型可以參考官方文檔
ShareUtils.java
public static final String PACKAGE_WECHAT = "com.tencent.mm"; /** * 分享文件到微信好友 by WXAPI * * @param thumbId 分享到微信顯示的圖標(biāo) */ public static void shareFileToWechat(Context context, File file, int thumbId) { if (!isInstallApp(context, ShareUtils.PACKAGE_WECHAT)) { Toast.makeText(context, "您需要安裝微信客戶端", Toast.LENGTH_LONG).show(); return; } //構(gòu)建發(fā)送文件體 WXFileObject fileObject = new WXFileObject(); byte[] fileBytes = readFile(file); //設(shè)置需要發(fā)送的文件byte[] fileObject.setFileData(fileBytes); fileObject.setFilePath(file.getAbsolutePath()); //使用媒體消息分享 WXMediaMessage msg = new WXMediaMessage(fileObject); //這個(gè)title有講究,最好設(shè)置為帶后綴的文件名,否則可能分享到微信后無(wú)法讀取 msg.title = file.getName(); //設(shè)置顯示的預(yù)覽圖 需小于32KB if (thumbId <= 0) thumbId = R.mipmap.ic_launcher; msg.thumbData = readBitmap(context, thumbId); //發(fā)送請(qǐng)求 SendMessageToWX.Req req = new SendMessageToWX.Req(); //創(chuàng)建唯一標(biāo)識(shí) req.transaction = String.valueOf(System.currentTimeMillis()); req.message = msg; req.scene = SendMessageToWX.Req.WXSceneSession; //WXSceneSession:分享到對(duì)話 // 通過(guò)WXAPIFactory工廠,獲取IWXAPI的實(shí)例 IWXAPI api = WXAPIFactory.createWXAPI(context, WXEntryActivity.APP_ID, true); // 將應(yīng)用的appId注冊(cè)到微信 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; } //關(guān)閉讀取file private static void closeQuietly(Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (Exception exception) { exception.printStackTrace(); } }
效果如下:
二、調(diào)用系統(tǒng)分享方法,把文件直接發(fā)送到微信
此種方式的好處就是不依賴微信SDK,調(diào)用系統(tǒng)提供的分享彈窗來(lái)分享到微信。
/** * 直接文件到微信好友 * * @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版本高過(guò)7.0(包括7.0版本) //當(dāng)前APP是不能直接向外部應(yīng)用提供file開頭的的文件路徑, //需要通過(guò)FileProvider轉(zhuǎn)換一下。否則在7.0及以上版本手機(jī)將直接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(); } } // 建立一個(gè)文件類型與文件后綴名的匹配表 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通過(guò)微信分享文件的2種解決方式。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Kotlin標(biāo)準(zhǔn)函數(shù)與靜態(tài)方法基礎(chǔ)知識(shí)詳解
Kotlin中的標(biāo)準(zhǔn)函數(shù)指的是Standard.kt文件中定義的函數(shù),任何Kotlin代碼都可以自由地調(diào)用所有的標(biāo)準(zhǔn)函數(shù)。例如let這個(gè)標(biāo)準(zhǔn)函數(shù),他的主要作用就是配合?.操作符來(lái)進(jìn)行輔助判空處理2022-11-11Android 動(dòng)態(tài)的顯示時(shí)間
本文給大家分享一段代碼實(shí)現(xiàn)android動(dòng)態(tài)顯示時(shí)間,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2016-12-12Kotlin中空判斷與問(wèn)號(hào)和感嘆號(hào)標(biāo)識(shí)符使用方法
最近使用kotlin重構(gòu)項(xiàng)目,遇到了一個(gè)小問(wèn)題,在Java中,可能會(huì)遇到判斷某個(gè)對(duì)象是否為空,為空?qǐng)?zhí)行一段邏輯,不為空?qǐng)?zhí)行另外一段邏輯,下面這篇文章主要給大家介紹了關(guān)于Kotlin中空判斷與問(wèn)號(hào)和感嘆號(hào)標(biāo)識(shí)符處理操作的相關(guān)資料,需要的朋友可以參考下2022-12-12Android中WebView無(wú)法后退和js注入漏洞的解決方案
這篇文章主要介紹了Android中WebView無(wú)法后退和js注入漏洞解決方案,其中js注入主要針對(duì)安卓4.2及以下版本中WebView的漏洞,需要的朋友可以參考下2016-02-02Android recyclerView橫條指示器實(shí)現(xiàn)淘寶菜單模塊
這篇文章主要為大家詳細(xì)介紹了recyclerView橫條指示器實(shí)現(xiàn)淘寶菜單模塊,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-02-02Android如何讓W(xué)ebView中的HTML5頁(yè)面實(shí)現(xiàn)視頻全屏播放
最近在工作遇到一個(gè)需求,需要讓W(xué)ebView中的HTML5頁(yè)面實(shí)現(xiàn)視頻全屏播放的效果,通過(guò)查找相關(guān)的資料終于找到了解決的方法,所以想著分享給大家,所以本文介紹了關(guān)于Android如何讓W(xué)ebView中的HTML5頁(yè)面實(shí)現(xiàn)視頻全屏播放的相關(guān)資料,需要的朋友可以參考學(xué)習(xí)。2017-04-04