美文网首页
Android 微信好友分享&朋友圈分享

Android 微信好友分享&朋友圈分享

作者: Joey_Zjy | 来源:发表于2019-07-21 23:33 被阅读0次
    最近在做公司一个商城项目,涉及到了微信分享,上网找了几篇博客看了看,总结下做个无脑教程,算是自己的一个总结,不喜勿喷,有错欢迎指出。

    所需材料

    一份导包:

    implementation 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
    

    五份权限:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    

    class文件两个:

    微信分享文件.png
    appID一个:这个需要在微信开发平台注册自己的app,具体前往这里查看
    以上就是所有所需的东西,接下来开始动手把代码打上再调用就可以了

    WXEntryActivity.class

    这个class是

    public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
    
        private IWXAPI api;
        private WXShare wxShare;
        String flag;
        String url;
        String title;
        String content;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.fragment_share_item);//这个布局文件随便放一个透明的就行
            flag=getIntent().getStringExtra("flag");//1:分享至朋友圈;0:分享至好友
            url=getIntent().getStringExtra("url");
            title=getIntent().getStringExtra("title");
            content=getIntent().getStringExtra("content");
            wxShare = new WXShare(this);
            wxShare.setListener(new OnResponseListener() {
                @Override
                public void onSuccess() {
    
                }
    
                @Override
                public void onCancel() {
    
                }
    
                @Override
                public void onFail(String message) {
    
                }
            });
            Log.e("WXEntryActivity", "WXEntryActivity");
            WXShare share = new WXShare(this);
            api = share.getApi();
            wxShare.share(flag,"这是要分享的文字");//分享文本
            if (flag.equals("0")){
                wxShare.shareUrl(0,this,url,title,content);//分享链接
            }else {
                wxShare.shareUrl(1, this, url, title, content);
            }
            //注意:
            // 第三方开发者如果使用透明界面来实现WXEntryActivity,
            // 需要判断handleIntent的返回值,如果返回值为false,
            // 则说明入参不合法未被SDK处理,应finish当前透明界面,避
            // 免外部通过传递非法参数的Intent导致停留在透明界面,
            // 引起用户的疑惑
            try {
                if (!api.handleIntent(getIntent(), this)) {
                    finish();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            wxShare.register();
        }
    
        @Override
        protected void onDestroy() {
            wxShare.unregister();
            super.onDestroy();
        }
    
        @Override
        protected void onNewIntent(Intent intent) {
            super.onNewIntent(intent);
            Log.e("onNewIntent", "onNewIntent");
            setIntent(intent);
            if (!api.handleIntent(intent, this)) {
                finish();
            }
        }
    
        @Override
        public void onReq(BaseReq baseReq) {
    
        }
    
        @Override
        public void onResp(BaseResp baseResp) {
            Intent intent = new Intent(WXShare.ACTION_SHARE_RESPONSE);
            intent.putExtra(WXShare.EXTRA_RESULT, new Response(baseResp));
            sendBroadcast(intent);
            finish();
        }
    
    

    WXshare.class

    public class WXShare {
        public static final String APP_ID = "这里填你注册成功的微信appid";
        public static final String ACTION_SHARE_RESPONSE = "action_wx_share_response";
        public static final String EXTRA_RESULT = "result";
        private final Context context;
        private final IWXAPI api;
        private OnResponseListener listener;
        private ResponseReceiver receiver;
    
        public WXShare(Context context) {
            api = WXAPIFactory.createWXAPI(context, APP_ID);
            this.context = context;
        }
    
        public WXShare register() {
            // 微信分享
            api.registerApp(APP_ID);
            receiver = new ResponseReceiver();
            IntentFilter filter = new IntentFilter(ACTION_SHARE_RESPONSE);
            context.registerReceiver(receiver, filter);
            return this;
        }
    
        public void unregister() {
            try {
                api.unregisterApp();
                context.unregisterReceiver(receiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
      //分享文本
        public WXShare share(int flag,String text) {
            WXTextObject textObj = new WXTextObject();
            textObj.text = text;
    
            WXMediaMessage msg = new WXMediaMessage();
            msg.mediaObject = textObj;
            //        msg.title = "Will be ignored";
            msg.description = text;
    
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("text");
            req.message = msg;
            req.scene= flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
    
            boolean result = api.sendReq(req);
            Log.e("text shared: " + result, "");
            return this;
        }
    
        //flag用来判断是分享到微信好友还是分享到微信朋友圈,
        //0代表分享到微信好友,1代表分享到朋友圈
        //分享链接
        public WXShare shareUrl(int flag, Context context, String url, String title, String descroption) {
            //初始化一个WXWebpageObject填写url
            WXWebpageObject webpageObject = new WXWebpageObject();
            webpageObject.webpageUrl = url;
            //用WXWebpageObject对象初始化一个WXMediaMessage,天下标题,描述
            WXMediaMessage msg = new WXMediaMessage(webpageObject);
            msg.title = title;
            msg.description = descroption;
            //这块需要注意,图片的像素千万不要太大,不然的话会调不起来微信分享,
            //我在做的时候和我们这的UIMM说随便给我一张图,她给了我一张1024*1024的图片
            //当时也不知道什么原因,后来在我的机智之下换了一张像素小一点的图片好了!
            Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo);
            msg.setThumbImage(thumb);
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
            api.sendReq(req);
            return this;
        }
    
        public IWXAPI getApi() {
            return api;
        }
    
        public void setListener(OnResponseListener listener) {
            this.listener = listener;
        }
    
        private String buildTransaction(final String type) {
            return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
        }
        private class ResponseReceiver extends BroadcastReceiver {
    
            @Override
            public void onReceive(Context context, Intent intent) {
                Response response = intent.getParcelableExtra(EXTRA_RESULT);
                Log.e("type: " + response.getType(),"type: " + response.getType());
                Log.e("errCode: " + response.errCode,"errCode: " + response.errCode);
                String result;
                if (listener != null) {
                    if (response.errCode == BaseResp.ErrCode.ERR_OK) {
                        listener.onSuccess();
                    } else if (response.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
                        listener.onCancel();
                    } else {
                        switch (response.errCode) {
                            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                                result = "发送被拒绝";
                                break;
                            case BaseResp.ErrCode.ERR_UNSUPPORT:
                                result = "不支持错误";
                                break;
                            default:
                                result = "发送返回";
                                break;
                        }
                        listener.onFail(result);
                    }
                }
            }
        }
    }
    

    调用

    Intent intent = new Intent(getActivity(), WXEntryActivity.class);
                    intent.putExtra("flag", "1");
                    intent.putExtra("title","链接的标题");
                    intent.putExtra("content", "链接的介绍");
                    intent.putExtra("url", "你要分享的链接");
    startActivity(intent);
    

    其实就是一个简单的Activity跳转加传值

    成果

    微信分享结果.jpg 微信分享朋友圈.jpg

    相关文章

      网友评论

          本文标题:Android 微信好友分享&朋友圈分享

          本文链接:https://www.haomeiwen.com/subject/xrhblctx.html