剛才客服問我發(fā)生什么事了,我說怎么回事婴噩,給我發(fā)了幾張截圖擎场。
我一看!嗷几莽!原來是微信分享出問題了迅办。
他們說,誒...用戶發(fā)來得截圖章蚣,你能不能看看站欺。
我說可以,我說你讓用戶看看他的手機(jī)是什么版本。
我一說完他啪就發(fā)來一張截圖矾策,很快傲渍恕!
我一看是Android11系統(tǒng)贾虽。
然后上來我去查看google官方文檔逃糟,發(fā)現(xiàn)Android 11 應(yīng)用訪問文件權(quán)限變更了
我全部明白了啊,需要使用FileProvider蓬豁。
明白了以后自然是開始寫代碼
AndroidManifest.xml 添加ShareProvider配置
<provider
android:name=".utils.WeChatShareProvider"
android:authorities="${applicationId}.wechatShare"
android:exported="false"
android:grantUriPermissions="true"
tools:replace="name,authorities,exported,grantUriPermissions">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/wechat_share_provider_paths"
tools:replace="name,resource" />
</provider>
wechat_share_provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="sharedata" path="shareData/"/>
</paths>
WeChatShareProvider.java
public class WeChatShareProvider extends FileProvider {
}
微信分享工具類
public class WechatUtils {
private IWXAPI api;
private Context context;
public static WechatUtils getInstance(Context context) {
if (wechatUtils == null) {
wechatUtils = new WechatUtils(context);
}
return wechatUtils;
}
public WechatUtils(Context mContext) {
this.context = mContext;
api = WXAPIFactory.createWXAPI(context, WEIXIN_ID, true);
}
public void sendImageToWeiXin(Bitmap bitmap, int scene) {
//這里添加微信安裝判斷
if (bitmap == null) {
return;
}
if (checkVersionValid() && checkAndroidNotBelowN()) {
// 使用contentPath作為文件路徑進(jìn)行分享
sendImageToWeiXinOs11(bitmap, scene);
} else {
// 使用原有方式傳遞文件路徑進(jìn)行分享
WXImageObject imageObject = new WXImageObject(bitmap);
WXMediaMessage msg = new WXMediaMessage(imageObject);
Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE, THUMB_SIZE, true);
bitmap.recycle();
msg.thumbData = bmpToByteArray(thumbBmp, true);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = "supplier";
req.message = msg;
req.scene = scene;
api.sendReq(req);
}
}
/**
* Android 11 微信圖片分享
* @param bitmap
* @param scene
*/
public void sendImageToWeiXinOs11(Bitmap bitmap, int scene) {
if (bitmap == null) {
return;
}
bitmapSaveFile(context, bitmap)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<File>() {
@Override
public void accept(File file) throws Exception {
String contentPath = getFileUri(context, file);
WXImageObject imageObject = new WXImageObject();
imageObject.setImagePath(contentPath);
WXMediaMessage msg = new WXMediaMessage(imageObject);
// 設(shè)置縮略圖
Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE, THUMB_SIZE, true);
bitmap.recycle();
msg.thumbData = bmpToByteArray(thumbBmp, true);
//構(gòu)建一個Req
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = "supplier";
req.message = msg;
req.scene = scene;
api.sendReq(req);
}
});
}
}
/**
* 注意绰咽,先清空文件夾文件
*
* @return
*/
public static Observable<File> bitmapSaveFile(@NonNull final Context context,
@NonNull final Bitmap bitmap) {
return Observable.create(new ObservableOnSubscribe<File>() {
@Override
public void subscribe(ObservableEmitter<File> emitter) throws Exception {
OutputStream outputStream = null;
try {
String fileName = "img_" + System.currentTimeMillis() + ".jpg";
final File screenshotsDir = new File(context.getExternalFilesDir(null), "shareData");
if (!screenshotsDir.exists()) { //如果該文件夾不存在,則進(jìn)行創(chuàng)建
screenshotsDir.mkdirs();//創(chuàng)建文件夾
}else {
for (File file : screenshotsDir.listFiles()) {
if (file.isFile()){
file.delete(); // 刪除所有文件
}
}
}
File screenshotFile = new File(screenshotsDir, fileName);
outputStream = new BufferedOutputStream(new FileOutputStream(screenshotFile));
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
outputStream.flush();
emitter.onNext(screenshotFile);
emitter.onComplete();
} catch (final IOException e) {
emitter.onError(e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (final IOException ignored) {
Log.e(TAG, "Failed to close OutputStream.");
}
}
}
}
}).subscribeOn(Schedulers.io());
}
public String getFileUri(Context context, File file) {
if (file == null || !file.exists()) {
return null;
}
Uri contentUri = FileProvider.getUriForFile(context,
context.getPackageName() + ".wechatShare", // 要與`AndroidManifest.xml`里配置的`authorities`一致庆尘,假設(shè)你的應(yīng)用包名為com.example.app
file);
// 授權(quán)給微信訪問路徑
context.grantUriPermission("com.tencent.mm", // 這里填微信包名
contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
return contentUri.toString(); // contentUri.toString() 即是以"content://"開頭的用于共享的路徑
}
// 判斷微信版本是否為7.0.13及以上
public boolean checkVersionValid() {
return api.getWXAppSupportAPI() >= 0x27000D00;
}
// 判斷Android版本是否11 及以上
public boolean checkAndroidNotBelowN() {
return android.os.Build.VERSION.SDK_INT >= 30;
}
到此代碼已經(jīng)寫完了剃诅,我稍微分析一下原因,微信分享WXImageObject 有兩種引用圖片方式驶忌,bitmap和url矛辕,如果傳的是bitmap按理說不存在存儲權(quán)限問題,但是也無法分享付魔,估計微信WXImageObject引用圖片的方式?jīng)]有做區(qū)分吧聊品。
這好嗎?這不好几苍!
我勸翻屈!想了想,沒啥好勸的妻坝。
謝謝朋友們伸眶!