目录
前言
客户方想要一个可以把app的二维码分享到微信的功能,这个二维码是apk的下载地址,以下是我总结的两种方式,不过我只使用了第一种,第二种我嫌麻烦还没用。
方式一
- 首先需要在AndroidManifest.xml中声明一下微信的包名,添加这个的作用是为了能在Android11以上可以判断手机是否安装了微信,如果你没有加的话可能会出现手机已经安装了微信但就是判断不出来。
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
.....
<queries>
<!-- 微信包名 -->
<package android:name="com.tencent.mm" />
</queries>
.....
</manifest>
- 根据包名判断是否安装了app的方法
/**
* 检查手机是否安装了指定软件
*
* @param context 上下文
* @param packageName 包名
* @return boolean
*/
public static boolean isAppInstalled(Context context, String packageName) {
if (TextUtils.isEmpty(packageName)){
return false;
}
try {
context.getPackageManager().getApplicationInfo(packageName,0);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
return true;
}
- 分享图片的代码示例
// 判断微信是否安装
boolean appInstalled = isAppInstalled(activity, "com.tencent.mm");
if (!appInstalled) {
// 替换为自己的Toast即可
ToastUtils.show("未安装微信无法分享!");
return;
}
// 获取资源的Uri 这里这么使用是因为我把二维码放在了drawable里
// 你只需要把要分享的图片得到Uri即可
Uri uri= getUriToResource(activity, R.drawable.qr);
// 跳转分享
Intent intent = new Intent();
ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
intent.setComponent(comp);
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "分享图片"));
获取资源Uri的方法(这个方法获取的是drawable和mipmap文件夹资源的Uri)
/**
* 获取资源的Uri
*
* @param context 上下文
* @param resId res id
* @return {@link Uri}
*/
public static Uri getUriToResource(@NonNull Context context,@AnyRes int resId) {
Resources resources = context.getResources();
return (new Uri.Builder())
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(resources.getResourcePackageName(resId))
.appendPath(resources.getResourceTypeName(resId))
.appendPath(resources.getResourceEntryName(resId))
.build();
}
方式二
这个方式需要集成微信的SDK,具体的请看开放平台的文档:
后续有使用到了再补充这方面的。。。
👍点赞,你的认可是我创作的动力 !
🌟收藏,你的青睐是我努力的方向!
✏️评论,你的意见是我进步的财富!