在包名下單獨(dú)建一個(gè)包 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";// 用于請(qǐng)求用戶信息的作用域
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(), "請(qǐng)求超時(shí)", 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("請(qǐng)稍后");
} 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后减拭,請(qǐng)求以下鏈接獲取access_token
private String GetCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
// 獲取用戶個(gè)人信息
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和實(shí)現(xiàn)IWXAPIEventHandler接口的對(duì)象傳遞給handleIntent方法
App.WXapi.handleIntent(this.getIntent(), this);
}
@Override
public void onReq(BaseReq baseReq) {
// finish();
}
/**
* 點(diǎn)擊確認(rèn)會(huì)回調(diào)的方法
* 第三方應(yīng)用發(fā)送到微信的請(qǐng)求處理后的響應(yīng)結(jié)果,會(huì)回調(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 請(qǐng)求碼
*/
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測(cè)試2222" + access_token);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
/**
* 獲取微信的個(gè)人信息
*
* @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();
}
}