简单的调起微信登录

首先呢,先导入依赖:

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

然后,创建包名(注意包名,必须创建成这样的)

然后在里边创建WXEntryActivity这个类

public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wxentry);
        getSupportActionBar().hide();
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //接收到分享以及登录的intent传递handleIntent方法,处理结果
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(this, 微信的appid, false);
        iwxapi.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {

        //登录回调
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                String code = ((SendAuth.Resp) baseResp).code;
                //获取accesstoken
                getAccessToken(code);
                Log.d("fantasychongwxlogin", code.toString()+ "");
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
                finish();
                break;
            default:
                finish();
                break;
        }
    }

    private void getAccessToken(String code) {
    }

在MainActivity里去调微信登录

public class MainActivity extends AppCompatActivity {

    private Button weixin;
    private static final String APP_ID = 微信的appid;

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        weixin = findViewById(R.id.weixin);
        //通过WXAPIFactory工厂获取IWXApI的示例
        api = WXAPIFactory.createWXAPI(this,APP_ID,true);
        //将应用的appid注册到微信
        api.registerApp(APP_ID);
        weixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";//
//                req.scope = "snsapi_login";//提示 scope参数错误,或者没有scope权限
                req.state = "wechat_sdk_微信登录";
                api.sendReq(req);
            }
        });
    }

在清单文件里配置activity


权限






你可能感兴趣的:(简单的调起微信登录)