安卓开发,微信登录页面代码
时间: 2023-11-13 19:07:18 浏览: 34
以下是微信登录页面的示例代码:
```
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private IWXAPI api;
private Button btnWechatLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnWechatLogin = findViewById(R.id.btn_wechat_login);
btnWechatLogin.setOnClickListener(this);
api = WXAPIFactory.createWXAPI(this, "你的微信AppID", true);
api.registerApp("你的微信AppID");
}
@Override
public void onClick(View v) {
if (v == btnWechatLogin) {
SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "wechat_login_demo";
api.sendReq(req);
}
}
@Override
protected void onResume() {
super.onResume();
// 处理微信登录回调
handleWechatLoginResult(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// 处理微信登录回调
handleWechatLoginResult(intent);
}
private void handleWechatLoginResult(Intent intent) {
if (intent != null) {
String action = intent.getAction();
if (action != null && action.equals(ConstantsAPI.ACTION_RESPONSE)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
int errCode = bundle.getInt(ConstantsAPI.ERR_CODE);
String errStr = bundle.getString(ConstantsAPI.ERR_MSG);
String code = bundle.getString(ConstantsAPI.AUTH_CODE);
if (errCode == BaseResp.ErrCode.ERR_OK) {
// TODO: 处理微信登录成功的逻辑
} else {
// TODO: 处理微信登录失败的逻辑
}
}
}
}
}
}
```
需要注意的是,此处的微信登录是通过调用微信开放平台提供的SDK实现的。在使用前,需要先在微信开放平台注册应用并获取AppID。同时,还需要在AndroidManifest.xml文件中配置以下内容:
```
<activity
android:name=".wxapi.WXEntryActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@android:style/Theme.Translucent.NoTitleBar"/>
<meta-data
android:name="com.tencent.mm.sdk.openapi.WXEntryActivity"
android:value=".wxapi.WXEntryActivity" />
<activity
android:name=".LoginActivity"
android:label="@string/title_activity_login"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="你的微信AppID"/>
</intent-filter>
</activity>
```