Android 微信分享,分享到朋友圈与分享到好友,以及微信登陆

extends:http://www.cnblogs.com/android100/p/Android-qq.html

一、申请你的AppID

http://open.weixin.qq.com/

  友情提示:推荐使用eclipse打包软件最后一步的MD5值去申请AppID

二、官网下载libammsdk.jar包

http://open.weixin.qq.com/download/?lang=zh_CN

三、将libammsdk.jar复制到工程的libs目录

Android 微信分享,分享到朋友圈与分享到好友,以及微信登陆

四、在需要分享的Activity编写代码 

private IWXAPI wxApi;  
//实例化  
wxApi = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID);  
wxApi.registerApp(Constants.WX_APP_ID);  
/** 
 * 微信分享 (这里仅提供一个分享网页的示例,其它请参看官网示例代码) 
 * @param flag(0:分享到微信好友,1:分享到微信朋友圈) 
 */  
private void wechatShare(int flag){  
    WXWebpageObject webpage = new WXWebpageObject();  
    webpage.webpageUrl = "这里填写链接url";  
    WXMediaMessage msg = new WXMediaMessage(webpage);  
    msg.title = "这里填写标题";  
    msg.description = "这里填写内容";  
    //这里替换一张自己工程里的图片资源  
    Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.share_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;  
    wxApi.sendReq(req);  
}  
//在需要分享的地方添加代码:  
wechatShare(0);//分享到微信好友  
wechatShare(1);//分享到微信朋友圈  
 

 

五、在你的包名相应目录下新建一个wxapi目录,并在该wxapi目录下新增一个WXEntryActivity类,该类继承自Activity,实现IWXAPIEventHandler接口

Android 微信分享,分享到朋友圈与分享到好友,以及微信登陆 
/** 微信客户端回调activity示例 */  
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {  
    // IWXAPI 是第三方app和微信通信的openapi接口  
    private IWXAPI api;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        api = WXAPIFactory.createWXAPI(this, "这里替换第一步申请的APP_ID", false);  
        api.handleIntent(getIntent(), this);  
        super.onCreate(savedInstanceState);  
    }  
    @Override  
    public void onReq(BaseReq arg0) { }  
  
    @Override  
    public void onResp(BaseResp resp) {  
        LogManager.show(TAG, "resp.errCode:" + resp.errCode + ",resp.errStr:"  
                + resp.errStr, 1);  
        switch (resp.errCode) {  
        case BaseResp.ErrCode.ERR_OK:  
            //分享成功  
            break;  
        case BaseResp.ErrCode.ERR_USER_CANCEL:  
            //分享取消  
            break;  
        case BaseResp.ErrCode.ERR_AUTH_DENIED:  
            //分享拒绝  
            break;  
        }  
    }  
}  

 

六、配置清单文件AndroidManifest.xml 

<activity    
    android:name=".wxapi.WXEntryActivity"  
    android:exported="true"  
    android:screenOrientation="portrait"   
    android:theme="@android:style/Theme.Translucent.NoTitleBar" />  

 

七、签名打包软件,然后可以测试了

 

/**
     * 微信分享
     *
     * @param flag(0:分享到微信好友,1:分享到微信朋友圈)
     */
    private void weChatShare(final int flag) {


        if (wxAPI != null && !wxAPI.isWXAppInstalled()) {
            AppUtils.showToast(mActivity, "您还未安装微信客户端呢");
            return;
        }
        ImageLoader.getInstance().loadImage(shareImageLink.replace("@100Q.jpg", "@100w_100h_1e_100Q.jpg|100x100-2rc.jpg"), new SimpleImageLoadingListener() {
            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                super.onLoadingComplete(imageUri, view, loadedImage);

                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = shareUrlLink;

                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title = shareTitle;
                msg.description = shareContent;
                //这里替换一张自己工程里的图片资源
                Bitmap thumb = loadedImage;
                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;
                wxAPI.sendReq(req);

                Log.e("Share", shareContent + shareTitle + shareUrlLink);
            }
        });
    }

-------------------------------------------------------------------------------登陆-----------------------------------------------------------------------------------------

 //Login start:
       IWXAPI WXAPI = WXAPIFactory.createWXAPI(this, AppConstants.KEY_WEIXIN_APP_ID, true); WXAPI.registerApp(AppConstants.KEY_WEIXIN_APP_ID); SendAuth.Req req = new SendAuth.Req(); req.scope = "snsapi_userinfo"; req.state = "wechat_sdk_demo"; WXAPI.sendReq(req);

 

WXEntryActivity

 // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI api;

    private Dialog progressDialog;// loading

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 通过WXAPIFactory工厂,获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, AppConstants.KEY_WEIXIN_APP_ID, true);
        api.registerApp(AppConstants.KEY_WEIXIN_APP_ID);
        api.handleIntent(getIntent(), this);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);
        api.handleIntent(intent, this);
    }

    // 微信发送请求到第三方应用时,会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
//                goToGetMsg();
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
//                goToShowMsg((ShowMessageFromWX.Req) req);
                break;
            default:
                break;
        }
    }

    // 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                progressDialog = DialogUtil.createLoadingDialog(this);
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.show();

//                SendAuth.Resp sendResp = (SendAuth.Resp) resp;

                Bundle bundle = new Bundle();
                resp.toBundle(bundle);
                SendAuth.Resp sp = new SendAuth.Resp(bundle);
                String code = sp.code;
                if (code != null && !code.equals("")) {
                    getAccessTokenFromWeiXin(code);
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                startLoginActivity("用户取消操作");
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                startLoginActivity("用户拒绝授权");
                break;
            default:
                break;
        }
    }

 

    private void getAccessTokenFromWeiXin(String code) {
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

        String requestUrlAppId = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AppConstants.KEY_WEIXIN_APP_ID;
        String requestUrlAppSecret = "&secret=" + AppConstants.KEY_WEIXIN_APP_SECRET;
        String requestUrlCode = "&code=" + code;
        String requestUrlLast = "&grant_type=authorization_code";

        String requestUrl = requestUrlAppId + requestUrlAppSecret + requestUrlCode + requestUrlLast;

        HttpUtil.get(requestUrl, null, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String content) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(content);
                    if (jsonObject.has("access_token") && jsonObject.has("openid")) {
                        String access_token = jsonObject.getString("access_token");
                        String openid = jsonObject.getString("openid");
                        getUserInfoFromWeiXin(access_token, openid);
                    } else {
                        AppUtils.showToast(WXEntryActivity.this, "授权失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) {
                AppUtils.showToast(WXEntryActivity.this, "请求失败,请检查网络重试");
            }

        });
    }

    //https://open.weixin.qq.com/cgi-bin/frame?t=resource/res_main_tmpl&verify=1&lang=zh_CN

    //            "openid":"OPENID",
//            "nickname":"NICKNAME",
//            "sex":1,
//            "province":"PROVINCE",
//            "city":"CITY",
//            "country":"COUNTRY",
//            "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
//            "privilege":[
//            "PRIVILEGE1",
//            "PRIVILEGE2"
//            ],
//            "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"
    private void getUserInfoFromWeiXin(String token, String openid) {
        //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + openid;
        HttpUtil.get(requestUrl, null, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String content) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(content);
                    if (jsonObject.has("nickname")) {
                        String openid = jsonObject.getString("openid");
                        String nickname = jsonObject.getString("nickname");
                        String sex = jsonObject.getString("sex");
                        String province = jsonObject.getString("province");
                        String city = jsonObject.getString("city");
                        String country = jsonObject.getString("country");
                        String headimgurl = jsonObject.getString("headimgurl");
                        String privilege = jsonObject.getString("privilege");
                        String unionid = jsonObject.getString("unionid");
                        postUserInfo2CBServer(unionid, sex, headimgurl, nickname, country, province, city);
                    } else {
                        AppUtils.showToast(WXEntryActivity.this, "授权失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable e) {
                AppUtils.showToast(WXEntryActivity.this, "请求失败,请检查网络重试");
            }
        });
    }

 

Android 微信分享,分享到朋友圈与分享到好友,以及微信登陆

上一篇:微信公众平台支持接收和发送微信小视频 微信小店产品展示更全方位


下一篇:iOS开发-仿微信图片分享界面实现