android ——第三方微信登錄

在包名下單獨建一個包 wxapi ? ===========


import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.support.annotation.Nullable;

import android.util.Log;

import android.view.View;

import android.widget.EditText;

import android.widget.FrameLayout;

import android.widget.ImageView;

import android.widget.TextView;

import android.widget.Toast;

import com.etcxc.android.R;

import com.etcxc.android.base.App;

import com.etcxc.android.base.BaseActivity;

import com.etcxc.android.utils.PrefUtils;

import com.etcxc.android.utils.ToastUtils;

import com.tencent.mm.sdk.openapi.SendAuth;

import java.io.IOException;

import java.io.InputStream;

import okhttp3.Call;

import okhttp3.Callback;

import okhttp3.OkHttpClient;

import okhttp3.Request;

import okhttp3.Response;

import static com.etcxc.android.R.id.editText1;

import static com.etcxc.android.R.id.editText2;

/**

* Created by 劉濤 on 2017/6/7 0007.

*/

public class Login2Activity extends BaseActivity implements View.OnClickListener {

protected final String TAG = ((Object) this).getClass().getSimpleName();

private boolean userTag;

private EditText f2_editText1;

private EditText f2_editText2;

private TextView f2_textView3;

private ImageView iv_wx_login;

private ImageView iv_qq_login;

public String userName;

public String passWord;

private Bitmap bitmap;

private FrameLayout flwx_user;

private FrameLayout fl_f2;

SendAuth.Req req;

private static final String WEIXIN_SCOPE = "snsapi_userinfo";// 用于請求用戶信息的作用域

private static final String WEIXIN_STATE = "login_state"; // 自定義

private static final int ERROR = 1;

private static final int SUCCESS = 2;

private TextView username;

private TextView usersex;

private ImageView head;

private TextView openid;

private Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

switch (msg.what) {

case SUCCESS:

head.setImageBitmap((Bitmap) msg.obj);

break;

case ERROR:

Toast.makeText(App.getContext(), "請求超時", Toast.LENGTH_SHORT).show();

break;

}

}

};

@Override

protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.login);

flwx_user = (FrameLayout) findViewById(R.id.flwx_user);

fl_f2 = (FrameLayout) findViewById(R.id.fl_f2);

username = (TextView) findViewById(R.id.tv_username);

usersex = (TextView) findViewById(R.id.tv_usersex);

head = (ImageView) findViewById(R.id.iv_userhead);

openid = (TextView) findViewById(R.id.tv_userid);

f2_editText1 = (EditText) findViewById(editText1);//用戶名

f2_editText2 = (EditText) findViewById(editText2);//密碼

f2_textView3 = (TextView) findViewById(R.id.textView3);//登錄

iv_wx_login = (ImageView) findViewById(R.id.iv_wx_login);

iv_qq_login = (ImageView) findViewById(R.id.iv_qq_login);

initview();

}

private void initview() {

userTag = PrefUtils.getBoolean(App.getContext(), "userTag", false);

if (userTag) {

//加載頭像url

String headurl = PrefUtils.getString(App.getContext(), "headurl", null);

flwx_user.setVisibility(View.VISIBLE);

fl_f2.setVisibility(View.INVISIBLE);

if (headurl != null)

SetWXUserInfo(headurl);

} else {

fl_f2.setVisibility(View.VISIBLE);

flwx_user.setVisibility(View.INVISIBLE);

}

f2_textView3.setOnClickListener(this);

iv_wx_login.setOnClickListener(this);

iv_qq_login.setOnClickListener(this);

userName = f2_editText1.getText().toString();

passWord = f2_editText2.getText().toString();

username.setText(PrefUtils.getString(App.getContext(), "username", null));

openid.setText(PrefUtils.getString(App.getContext(), "openid", null));

// headurl.setText(PrefUtils.getString(App.getContext(),"headurl",null));

if (PrefUtils.getInt(App.getContext(), "usersex", 1) == 1) {

usersex.setText("男");

} else {

usersex.setText("女");

}

}

private void SetWXUserInfo(final String url) {

new Thread() {

@Override

public void run() {

OkHttpClient uOkHttpClient = new OkHttpClient();

Request requst = new Request.Builder()

.url(url)

.get()

.build();

uOkHttpClient.newCall(requst).enqueue(new Callback() {

@Override

public void onFailure(Call call, IOException e) {

}

@Override

public void onResponse(Call call, Response response) throws IOException {

InputStream is = response.body().byteStream();//字節(jié)流

bitmap = BitmapFactory.decodeStream(is);

//使用Hanlder發(fā)送消息

Message msg = Message.obtain();

msg.what = SUCCESS;

msg.obj = bitmap;

handler.sendMessage(msg);

}

});

}

}.start();

}

@Override

public void onClick(View v) {

switch (v.getId()) {

case R.id.textView3:

ToastUtils.showToast("登錄成功");

break;

case R.id.iv_wx_login://微信登錄

WXLogin();

finish();

break;

case R.id.iv_qq_login://

QQLogin();

break;

}

}

/**

* 登錄微信

*/

private void WXLogin() {

if (App.WXapi != null && App.WXapi.isWXAppInstalled()) {

req = new SendAuth.Req();

req.scope = WEIXIN_SCOPE;

req.state = WEIXIN_STATE;

App.WXapi.sendReq(req);

Log.i(TAG, "。。。。。。。。。。。。WxLogin(),微信登錄。。。。。。。");

ToastUtils.showToast("請稍后");

} else

ToastUtils.showToast("用戶未安裝微信");

}

/**

* qq登錄

*/

private void QQLogin() {

}

@Override

public void onResume() {

super.onResume();

}

@Override

public void onStart() {

super.onStart();

}

}


package com.etcxc.android.ui.activity;

import android.content.Intent;

import android.os.Bundle;

import android.support.annotation.Nullable;

import android.support.v7.app.AppCompatActivity;

import android.widget.Toast;

import com.etcxc.android.base.App;

import com.etcxc.android.utils.LogUtil;

import com.etcxc.android.utils.PrefUtils;

import com.tencent.mm.sdk.openapi.BaseReq;

import com.tencent.mm.sdk.openapi.BaseResp;

import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;

import com.tencent.mm.sdk.openapi.SendAuth;

import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;

import okhttp3.Callback;

import okhttp3.OkHttpClient;

import okhttp3.Request;

import okhttp3.Response;

import static android.R.attr.path;

import static com.etcxc.android.base.App.WX_APP_ID;

import static com.etcxc.android.base.App.WX_APP_SECRET;

import static com.etcxc.android.base.App.userTag;

/**

* Created by 劉濤 on 2017/6/5 0005.

*/

public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

protected final String TAG = ((Object) this).getClass().getSimpleName();

private BaseResp resp = null;

// 獲取第一步的code后,請求以下鏈接獲取access_token

private String GetCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

// 獲取用戶個人信息

private String GetUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

private final OkHttpClient client = new OkHttpClient();

@Override

protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

App.WXapi = WXAPIFactory.createWXAPI(this, WX_APP_ID, false);

//將你收到的intent和實現(xiàn)IWXAPIEventHandler接口的對象傳遞給handleIntent方法

App.WXapi.handleIntent(this.getIntent(), this);

}

@Override

public void onReq(BaseReq baseReq) {

// finish();

}

/**

* 點擊確認(rèn)會回調(diào)的方法

* 第三方應(yīng)用發(fā)送到微信的請求處理后的響應(yīng)結(jié)果,會回調(diào)到該方法

*

* @param resp

*/

@Override

public void onResp(BaseResp resp) {

String result = "";

switch (resp.errCode) {

case BaseResp.ErrCode.ERR_OK:

result = "發(fā)送成功";

Toast.makeText(this, result, Toast.LENGTH_LONG).show();

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

if (sendResp != null) {

String code = sendResp.token;

getAccess_token(code);

}

userTag = true;

PrefUtils.setBoolean(App.getContext(), "userTag", userTag);

finish();

break;

case BaseResp.ErrCode.ERR_USER_CANCEL:

result = "發(fā)送取消";

Toast.makeText(this, result, Toast.LENGTH_LONG).show();

//finish();

break;

case BaseResp.ErrCode.ERR_AUTH_DENIED:

result = "發(fā)送被拒絕";

Toast.makeText(this, result, Toast.LENGTH_LONG).show();

//finish();

break;

default:

result = "發(fā)送返回";

Toast.makeText(this, result, Toast.LENGTH_LONG).show();

//finish();

break;

}

finish();

}

/**

* 獲取openid accessToken值用于后期操作

*

* @param code 請求碼

*/

private void getAccess_token(final String code) {

//用戶信息

String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="

+ WX_APP_ID

+ "&secret="

+ WX_APP_SECRET

+ "&code="

+ code

+ "&grant_type=authorization_code";

run(url);

}

public void run(String url) {

final Request request = new Request.Builder()

//.url("http://publicobject.com/helloworld.txt")

.url(url)

.get()

.build();

client.newCall(request).enqueue(new Callback() {

@Override

public void onFailure(Call call, IOException e) {

}

@Override

public void onResponse(Call call, Response response) throws IOException {

if (!response.isSuccessful()) ;

try {

String responseStr = response.body().string();

JSONObject jsonObject = new JSONObject(responseStr);

String openid = jsonObject.getString("openid").toString().trim();

String access_token = jsonObject.getString("access_token").toString().trim();

getUserMesg(access_token, openid);

//? ? ? ? ? ? ? ? String openid = jsonObject.getString("openid").toString().trim();

//? ? ? ? ? ? ? ? ? String access_token = jsonObject.getString("access_token").toString().trim();

//? ? ? ? ? ? ? ? ? LogUtil.i(TAG, "getUserMesg 拿到了用戶Wx基本信息.. nickname:" + openid + "asdasdasdadadadad測試2222" + access_token);

} catch (JSONException e) {

e.printStackTrace();

}

}

});

}

/**

* 獲取微信的個人信息

*

* @param access_token

* @param openid

*/

private void getUserMesg(final String access_token, final String openid) {

JSONObject jsonObject = null;

String url = "https://api.weixin.qq.com/sns/userinfo?access_token="

+ access_token

+ "&openid="

+ openid;

LogUtil.i(TAG, "getUserMesg:" + path);

try {

final Request request = new Request.Builder()

.url(url)

.get()

.build();

client.newCall(request).enqueue(new Callback() {

@Override

public void onFailure(Call call, IOException e) {

}

@Override

public void onResponse(Call call, Response response) throws IOException {

String responseStr = response.body().string();

try {

JSONObject jsonObject = new JSONObject(responseStr);

String nickname = jsonObject.getString("nickname");//名字

int sex = Integer.parseInt(jsonObject.get("sex").toString());//性別

String headimgurl = jsonObject.getString("headimgurl");? //頭像

String openid = jsonObject.getString("openid");

String unionid = jsonObject.getString("openid");

PrefUtils.setString(App.getContext(), "openid", openid);

PrefUtils.setString(App.getContext(), "username", nickname);

PrefUtils.setInt(App.getContext(), "usersex", sex);

PrefUtils.setString(App.getContext(), "headurl", headimgurl);

PrefUtils.setString(App.getContext(), "unionid", unionid);

LogUtil.i(TAG, "getUserMesg 拿到了用戶Wx基本信息:");

LogUtil.i(TAG, "名字.. nickname:" + nickname);

LogUtil.i(TAG, "性別.. nickname:" + sex);

LogUtil.i(TAG, "頭像:" + headimgurl);

//todo:不使用eventbus

//? ? ? ? ? ? ? ? ? ? ? ? EventBus.getDefault().post(new MessageEvent(nickname));

//拿到這些信息后進(jìn)行相應(yīng)的業(yè)務(wù)操作,提交服務(wù)器

} catch (JSONException e) {

e.printStackTrace();

}

}

});

} catch (Exception e) {

e.printStackTrace();

}

return;

}

@Override

protected void onNewIntent(Intent intent) {

super.onNewIntent(intent);

setIntent(intent);

App.WXapi.handleIntent(intent, this);

finish();

}

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,565評論 6 539
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,115評論 3 423
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 177,577評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,514評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,234評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,621評論 1 326
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,641評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,822評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,380評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,128評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,319評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,879評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,548評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,970評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,229評論 1 291
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,048評論 3 397
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,285評論 2 376

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,696評論 25 708
  • 在本文之前請先去官方下載SDK 如果你做了分享那就不需要了; 注:你做了分享的意思 是你在清單文件下面已經(jīng)注冊了所...
    sakura_L閱讀 2,869評論 0 1
  • 準(zhǔn)備材料:微信開發(fā)者賬號注冊你的APPlibammsdk.jar包debug.keystore文件 準(zhǔn)備工作 申請...
    Nickyzhang閱讀 11,761評論 18 31
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,814評論 18 139
  • 我不知道美好的愛情背后還有這么多沉重 甚至改變了我的一生
    塵埃木木閱讀 204評論 0 0