Android中实现微信分享的功能

在android开发中微信分享功能还是经常用到的,比如把文字,图片,网页类型,小程序类型的文件等分享给微信好友,朋友圈等。官方文档 那么接下来就来说说如何去实现吧

一.添加依赖
   implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
二. 写一个分享的页面(popup_share.xml)

这个是个popupWindow弹窗来着
在这里插入图片描述

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@drawable/content_corner"
    android:paddingTop="10dp"
    android:paddingBottom="15dp">
    <TextView
        android:text="分享到"
        android:gravity="center"
        android:textColor="@color/theme_defaultText"
        android:textSize="@dimen/order1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <LinearLayout
        android:layout_marginTop="10dp"
        android:layout_marginBottom="25dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:id="@+id/bottom_share_wechat"
            android:gravity="center"
            android:orientation="vertical"
            android:layout_weight="1.0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <com.example.chunjiafu.custom.ImageRound
                android:src="@drawable/wechat"
                android:scaleType="centerCrop"
                android:layout_width="50dp"
                android:layout_height="50dp"/>
            <TextView
                android:text="微信好友"
                android:textColor="@color/theme_defaultText"
                android:textSize="@dimen/order1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/bottom_share_wxcircle"
            android:gravity="center"
            android:orientation="vertical"
            android:layout_weight="1.0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <com.example.chunjiafu.custom.ImageRound
                android:src="@drawable/wechat_momemts"
                android:scaleType="centerCrop"
                android:layout_width="50dp"
                android:layout_height="50dp"/>
            <TextView
                android:text="朋友圈"
                android:textColor="@color/theme_defaultText"
                android:textSize="@dimen/order1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/bottom_share_qq"
            android:gravity="center"
            android:orientation="vertical"
            android:layout_weight="1.0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <com.example.chunjiafu.custom.ImageRound
                android:src="@drawable/qq"
                android:scaleType="centerCrop"
                android:layout_width="50dp"
                android:layout_height="50dp"/>
            <TextView
                android:text="QQ好友"
                android:textColor="@color/theme_defaultText"
                android:textSize="@dimen/order1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/bottom_share_qzone"
            android:gravity="center"
            android:orientation="vertical"
            android:layout_weight="1.0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <com.example.chunjiafu.custom.ImageRound
                android:src="@drawable/qq_qzone"
                android:scaleType="centerCrop"
                android:layout_width="50dp"
                android:layout_height="50dp"/>
            <TextView
                android:text="QQ空间"
                android:textColor="@color/theme_defaultText"
                android:textSize="@dimen/order1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/bottom_share_sina"
            android:gravity="center"
            android:orientation="vertical"
            android:layout_weight="1.0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <com.example.chunjiafu.custom.ImageRound
                android:src="@drawable/webo"
                android:scaleType="centerCrop"
                android:layout_width="50dp"
                android:layout_height="50dp"/>
            <TextView
                android:text="微博"
                android:textColor="@color/theme_defaultText"
                android:textSize="@dimen/order1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout>
    </LinearLayout>
    <TextView
        android:id="@+id/share_cancel"
        android:text="取消"
        android:textColor="@color/theme_defaultText"
        android:textSize="@dimen/order2"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>
三. 自定义一个类WeChatShareUtils(微信分享工具类)

这里写有文本,图片,网页,小程序等类型的分享,需要直接用就可以了

// todo 微信分享工具类
public class WeChatShareUtils {
//    private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001; // 微信4.2以上支持
    private static final int TIMELINE_SUPPORTED_VERSION = 0x27000D00;  // 判断微信版本是否为7.0.13及以上
    private static final String id = "xxxxxx"; //小程序原始id
    private static final String pageUrl = "xxxxxx"; //兼容低版本的网页链接


    //IWXAPI是第三方app和微信通信的openapi接口
    private IWXAPI api;
    private Context context;
    public static WeChatShareUtils weChatShareUtils;

    public static WeChatShareUtils getInstance(Context context){
        if(weChatShareUtils ==null){
            weChatShareUtils = new WeChatShareUtils();
        }
        if(weChatShareUtils.api !=null){
            weChatShareUtils.api.unregisterApp();;
        }
        weChatShareUtils.context = context;
        weChatShareUtils.regToWx();
        return weChatShareUtils;
    }

     // todo 注册应用id到微信
    private void regToWx(){
        //通过WXAPIFactory工厂,获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(context, Config.APPID,true);
        //将应用的appId注册到微信
        api.registerApp(Config.APPID);
    }

    /**
     *todo 分享文字到朋友圈或者好友
     * @param text 文本内容
     * @param scene 分享方式:好友还是朋友圈
     * @return
     */
    public boolean shareText(String text,int scene){
        //初始化一个WXTextObject对象,填写分享的文本对象
        WXTextObject textObject = new WXTextObject();
        textObject.text = text;
        return share(textObject,text,scene);
    }

    /**
     * todo 分享图片到朋友圈或者好友
     * @param bmp  图片的Bitmap对象
     * @param scene 分享方式:好友 WXSceneSession 还是朋友圈 WXSceneTimeline,收藏 WXSceneFavorite
     * @return
     */
    public boolean sharePic(Bitmap bmp, int scene){
        //初始化一个WXImageObject对象
        WXImageObject imageObject = new WXImageObject();
        //设置缩略图
        Bitmap thump = Bitmap.createScaledBitmap(bmp,300,300,true);
        bmp.recycle();
        return share(imageObject,thump,scene);
    }

    /**
     * todo 分享网页到朋友圈或者好友,视频和音乐的分享和网页大同小异,只是创建的对象不同。
     * @param url 网页的url
     * @param title 显示分享网页的标题
     * @param thumb 图片的缩略图
     * @param description 对网页的描述
     * @param scene 分享方式:好友还是朋友圈
     * @return
     */
    public boolean shareUrl(String url, String title, Bitmap thumb, String description, int scene) {
        //初试话一个WXWebpageObject对象,填写url
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = url;
        //设置缩略图
        Bitmap tmb = Bitmap.createScaledBitmap(thumb,150,150,true);
        thumb.recycle();
        return share(webPage, title, tmb, description, scene);
    }

    /**
     * todo 分享小程序类型
     * @param url
     * @param title
     * @param thumb
     * @param description
     * @param scene 只支持分享给微信好友
     * @return
     */
    public boolean shareMiniProgram(String url, String title, Bitmap thumb, String description, int scene) {
        //初试话一个WXMiniProgramObject对象,填写url
        WXMiniProgramObject wxMiniProgramObject = new WXMiniProgramObject();
        wxMiniProgramObject.webpageUrl = pageUrl; //兼容低版本的网页链接
        wxMiniProgramObject.miniprogramType = WXMiniProgramObject.MINIPROGRAM_TYPE_TEST; //小程序类型,测试版
        wxMiniProgramObject.userName = id;  //小程序原始id
        wxMiniProgramObject.path = url; //小程序的path

        //设置缩略图
        Bitmap tmb = Bitmap.createScaledBitmap(thumb,300,300,true);
        thumb.recycle();
        return share(wxMiniProgramObject, title, tmb, description, scene);
    }


    private boolean share(WXMediaMessage.IMediaObject mediaObject, Bitmap thumb, int scene) {
        return share(mediaObject, null, thumb, null, scene);
    }

    private boolean share(WXMediaMessage.IMediaObject mediaObject, String description, int scene) {
        return share(mediaObject, null, null, description, scene);
    }

    private boolean share(WXMediaMessage.IMediaObject mediaObject,String title,Bitmap thumb,String description, int scene){
        WXMediaMessage msg = new WXMediaMessage(mediaObject);
        if(title !=null){
            msg.title = title;
        }
        if(description !=null){
            msg.description = description;
        }
        if(thumb !=null){
            msg.thumbData = bmpToByteArray(thumb, true);
        }
        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = scene;
        return api.sendReq(req);
    }

    //判断是否支持转发到朋友圈
    //微信4.2以上支持,如果需要检查微信版本支持API的情况, 可调用IWXAPI的getWXAppSupportAPI方法,0x21020001及以上支持发送朋友圈
    //微信版本:当且仅当通过 IWXAPI.getWXAppSupportAPI() 接口获取到的值 >= 0x27000D00(7.0.13以上),才能支持FileProvider的方式进行分享。
    public boolean isSupportWX(){
        int wxSdkVersion = api.getWXAppSupportAPI();
        return wxSdkVersion >= TIMELINE_SUPPORTED_VERSION;
    }

    // todo Bitmap转换为 byte数组
    private byte[] bmpToByteArray(final Bitmap bmp,final boolean needRecycle){
        int i;
        int j;
        if (bmp.getHeight() > bmp.getWidth()) {
            i = bmp.getWidth();
            j = bmp.getWidth();
        }  else {
            i = bmp.getHeight();
            j = bmp.getHeight();
        }

        Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
        Canvas localCanvas =  new Canvas(localBitmap);

        while ( true) {
            localCanvas.drawBitmap(bmp,  new Rect(0, 0, i, j),  new Rect(0, 0,i, j),  null);
            if (needRecycle)
                bmp.recycle();
            ByteArrayOutputStream localByteArrayOutputStream =  new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
            try {
                localByteArrayOutputStream.close();
                return arrayOfByte;
            }  catch (Exception e) {
                // F.out(e);
            }
            i = bmp.getHeight();
            j = bmp.getHeight();
        }
    }
}

四. 新建WXEntryActivity(分享回调)

注意,一定是放在wxapi下面的,且一定是要WXEntryActivity这个类名,错一个字都不行
在这里插入图片描述

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI api;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setStatusBarColor(Color.parseColor("#000000"));
        api = WXAPIFactory.createWXAPI(getApplicationContext(), Config.APPID, true);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(getIntent(), this);
        WXEntryActivity.this.finish();
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp resp) {
        if(resp.getType() == ConstantsAPI.COMMAND_SENDAUTH){
           //微信登录
        }else if(resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX){
           //微信分享
            String result = "";
            switch (resp.errCode){
                case BaseResp.ErrCode.ERR_OK:
                    result = "分享成功";
                    break;
                default:
                    result = "分享失败";
                    break;

            }
            ToolUtils.midToast(getApplicationContext(),result,1000);
        }
        WXEntryActivity.this.finish();
    }
}
五. 使用
 @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
           case R.id.bottom_share_wechat: //微信分享
                sharePopupWindow.dismiss();
                fun_handleShare(SendMessageToWX.Req.WXSceneSession);
                break;
            case R.id.bottom_share_wxcircle: //朋友圈
                 sharePopupWindow.dismiss();        
                 fun_handleShare1(SendMessageToWX.Req.WXSceneTimeline);
                break;
            case R.id.bottom_share_qq: //qq
                Toast.makeText(getApplicationContext(),"抱歉亲,暂时不支持转发给QQ好友",Toast.LENGTH_SHORT).show();
                break;
            case R.id.bottom_share_qzone: //qq空间
                Toast.makeText(getApplicationContext(),"抱歉亲,暂时不支持转发至QQ空间",Toast.LENGTH_SHORT).show();
                break;
            case R.id.bottom_share_sina: //微博
                Toast.makeText(getApplicationContext(),"抱歉亲,暂时不支持转发至微博",Toast.LENGTH_SHORT).show();
                break;
        }


   // todo fun_handleShare 分享小程序类型 (只支持分享给微信好友)
    private void fun_handleShare(int scene){
        if(weChatShareUtils.isSupportWX()){
                String desc = "我在xxxx发现了一个不错的商品,赶快来看看吧。";
                String title = "男士休闲裤";
                String url = "/pages/media?xx=12";
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.logo_good);
                weChatShareUtils.shareMiniProgram(url,title,bitmap,desc,scene);
        }else{
            ToolUtils.midToast(getApplicationContext(),"手机上微信版本不支持分享功能",1000);
        }
    }
    
 // todo 分享网页类型
    private void fun_handleShare1(int scene){
        if(weChatShareUtils.isSupportWX()){
                String desc = "我在发现了xxx一个不错的商品,赶快来看看吧。";
                String title = "男士休闲裤";
                String url = "http://www.baidu.com";
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.logo_good);
                weChatShareUtils.shareUrl(url,title,bitmap,desc,scene);
        }else{
            ToolUtils.midToast(getApplicationContext(),"手机上微信版本不支持分享功能",1000);
        }
    }

按上面的方法已经如果不出意外,是正常分享出去了。
但是,有没发现,我上面分享出去的是个本地图片,且缩略图官方仅支持加载本地的bitmap。

那么问题就来,如果我的是张网络图片(从后台取回来的图片url)那要怎么办呢?

办法自然是有的,就是把这个网络图片下载到本地保存成bitmap不就可以了么,太调皮了哈哈哈哈哈哈。
如何把网络图片下载到本地并保存成bitmap呢,请移步【另一篇》网络图片转化为bitmap】

  • 5
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
要在 Android 应用程序实现分享微信功能,可以使用微信官方提供的 SDK,具体步骤如下: 1. 在微信开放平台注册开发者账号,并创建应用,获取 AppID。 2. 在应用的 build.gradle 文件添加以下依赖: ``` implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+' ``` 3. 在 AndroidManifest.xml 文件添加以下代码: ``` <!-- 注册微信 SDK --> <activity android:name=".wxapi.WXEntryActivity" android:exported="true" android:launchMode="singleInstance" android:taskAffinity="${applicationId}" android:theme="@android:style/Theme.Translucent.NoTitleBar" /> <meta-data android:name="com.tencent.mm.sdk.openapi.IWXAPI_APPID" android:value="替换为你的 AppID" /> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="wx替换为你的 AppID" /> </intent-filter> ``` 4. 创建一个实现了 IWXAPIEventHandler 接口的 Activity,并在其处理微信回调。 5. 在需要进行分享的地方,调用以下代码: ``` // 初始化微信 API IWXAPI api = WXAPIFactory.createWXAPI(context, "替换为你的 AppID", true); api.registerApp("替换为你的 AppID"); // 创建分享消息对象 WXMediaMessage message = new WXMediaMessage(); message.title = "分享标题"; message.description = "分享描述"; // 设置消息缩略图 Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.thumb); message.thumbData = Util.bmpToByteArray(thumb, true); // 创建网页对象 WXWebpageObject webpage = new WXWebpageObject(); webpage.webpageUrl = "http://www.example.com/"; message.mediaObject = webpage; // 构造一个Req SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("webpage"); req.message = message; req.scene = SendMessageToWX.Req.WXSceneSession; // 分享到会话 // 调用api接口,发送数据到微信 api.sendReq(req); ``` 其,Util.bmpToByteArray() 是一个将 Bitmap 转换为 byte[] 的工具方法,可以自行实现。另外,buildTransaction() 方法是一个生成唯一标识符的工具方法,可以使用当前时间戳等方式实现。 以上就是在 Android 应用程序实现分享微信的基本步骤。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值