第三方微信登录,分享
程序员文章站
2022-06-12 20:23:55
...
清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bw.movie">
<uses-permission android:name="android.permission.INTERNET" />
<!-- for mta statistics, not necessary-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".wxapi.WXEntryActivity"
android:label="@string/app_name"
android:exported="true"
android:taskAffinity="net.sourceforge.simcpux"
android:launchMode="singleTask">
</activity>
</application>
</manifest>
MianActivity
package com.bw.movie;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import static com.tencent.mm.opensdk.modelmsg.SendMessageToWX.Req.WXSceneSession;
import static com.tencent.mm.opensdk.modelmsg.SendMessageToWX.Req.WXSceneTimeline;
public class MainActivity extends AppCompatActivity {
// APP_ID 替换为你的应用从官方网站申请到的合法appID
private static final String APP_ID = "wxb3852e6a6b7d9516";
// IWXAPI 是第三方app和微信通信的openApi接口
private IWXAPI api;
private Button login;
private Button fenxiang;
private int i=1;
private int y=2;
private void regToWx() {
// 通过WXAPIFactory工厂,获取IWXAPI的实例
api = WXAPIFactory.createWXAPI(this, APP_ID, true);
// 将应用的appId注册到微信
api.registerApp(APP_ID);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
regToWx();
login = findViewById(R.id.login);
fenxiang = findViewById(R.id.fenxiang);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
wxlogin();
}
});
fenxiang.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
wxfengxiangContent();
//带图片的分享被注释掉了
//wxShareImg();
}
});
}
// private void wxShareImg() {
// shared(false, "你好啊", "哈哈哈", "http://www.vipandroid.cn", "http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKon4Vic7QoV4tawbSZiagLMicCyVc04Usw78aib5MkYF52ORx6osco8nyXKhoWXhib2u8WLUyibQsrKa4A/132");
// }
// private void shared(final boolean friendsCircle, final String title, final String desc, final String link, final String pictrue) {
// new Thread() {
//
// @Override
// public void run() {
// super.run();
// WXWebpageObject webpage = new WXWebpageObject();
// webpage.webpageUrl = link;//分享url
// WXMediaMessage msg = new WXMediaMessage(webpage);
// msg.title = title;
// msg.description = desc;
// try {
// Bitmap bitmap = BitmapFactory.decodeStream(new URL(pictrue).openStream());
// Bitmap thumBitmap = bitmap.createScaledBitmap(bitmap, 60, 60, true);
//// 释放资源
// bitmap.recycle();
// msg.thumbData = bmpToByteArray(thumBitmap, true);
// SendMessageToWX.Req req = new SendMessageToWX.Req();
// req.transaction = String.valueOf(System.currentTimeMillis());
// req.message = msg;
// req.scene = friendsCircle ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
// api.sendReq(req);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
//
//
// }
// }.start();
// }
private void wxfengxiangContent() {
//初始化一个 WXTextObject 对象,填写分享的文本内容
WXTextObject textObj = new WXTextObject();
textObj.text = "我是微信分享";
//用 WXTextObject 对象初始化一个 WXMediaMessage 对象
WXMediaMessage msg = new WXMediaMessage();
msg.mediaObject = textObj;
msg.description = "我是微信分享内容";
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = String.valueOf(System.currentTimeMillis()); //transaction字段用与唯一标示一个请求
req.message = msg;
if (api.getWXAppSupportAPI() >= Build.TIMELINE_SUPPORTED_SDK_INT) {
//do share
//分享到微信朋友圈 WXSceneTimeline 分享到微信好友 WXSceneSession
req.scene = WXSceneTimeline;
}
//调用api接口,发送数据到微信
api.sendReq(req);
}
private void wxlogin() {
// send oauth request
SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = "wechat_sdk_demo_test";
api.sendReq(req);
}
//bitmap转byte数组
// public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
// int i;
// int j;
// if (bmp.getHeight() > bmp.getWidth()) {
// i = bmp.getWidth();
// j = bmp.getWidth();
// } else {
// i = bmp.getHeight();
// j = bmp.getHeight();
// }
//
// Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
// Canvas localCanvas = new Canvas(localBitmap);
//
// while (true) {
// localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0, i, j), null);
// if (needRecycle)
// bmp.recycle();
// ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
// localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
// localByteArrayOutputStream);
// localBitmap.recycle();
// byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
// try {
// localByteArrayOutputStream.close();
// return arrayOfByte;
// } catch (Exception e) {
// // F.out(e);
// }
// i = bmp.getHeight();
// j = bmp.getHeight();
// }
// }
}
MianActivity的xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/login"
android:text="登陆"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/fenxiang"
android:text="分享"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
微信api
package com.bw.movie.wxapi;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import com.bw.movie.R;
import com.bw.movie.bean.Token;
import com.bw.movie.net.OkHttputils;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
//微信的回调
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {
// APP_ID 替换为你的应用从官方网站申请到的合法appID
private static final String APP_ID = "wxb3852e6a6b7d9516";
// IWXAPI 是第三方app和微信通信的openApi接口
private IWXAPI api;
private void regToWx() {
// 通过WXAPIFactory工厂,获取IWXAPI的实例
api = WXAPIFactory.createWXAPI(this, APP_ID, true);
// 将应用的appId注册到微信
api.registerApp(APP_ID);
api.handleIntent(getIntent(), this);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wx);
regToWx();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
api.handleIntent(getIntent(), this);
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp resp) {
if(resp.getType()== ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX){//分享
Log.i("ansen","微信分享操作.....");
}else if(resp.getType()==ConstantsAPI.COMMAND_SENDAUTH){//登陆
Log.i("ansen", "微信登录操作.....");
SendAuth.Resp authResp = (SendAuth.Resp) resp;
String code=authResp.code;
doLogin(code);
}
}
private void doLogin(String code) {
String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APP_ID+"&secret=SECRET&code="+code+"&grant_type=authorization_code";
new OkHttputils().get(url).result(new OkHttputils.HttpLisenter() {
@Override
public void success(String data) {
Token token = new Gson().fromJson(data, Token.class);
token.getAccess_token();
}
@Override
public void fail() {
}
});
}
}
微信api的xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="l就是把分辨率低不就爱的壁画不定积分"/>
</LinearLayout>
到依赖
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0'
//到依赖
classpath 'com.github.dcendents:android-maven-gradle-plugin:2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
OKHTTP封装
package com.bw.movie.net;
import android.os.Handler;
import android.os.Message;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class OkHttputils {
int HTTTP_SUCCESS=1000;
int HTTP_FAIL=1001;
private HttpLisenter httpLisenter;
public OkHttputils get(String url){
init(url,0,null);
return this;
}
public OkHttputils post(String url,FormBody.Builder bodybuilder){
init(url,1,bodybuilder);
return this;
}
private void init(String url, int type,FormBody.Builder bodybuilder) {
OkHttpClient client=new OkHttpClient();
Request.Builder builder = new Request.Builder();
builder.url(url);
if(type==0){
builder.get();
}else {
RequestBody body=bodybuilder.build();
builder.post(body);
}
Request request=new Request.Builder().build();
final Message message=new Message();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
message.what=HTTP_FAIL;
handler.sendMessage(message);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
message.what=HTTTP_SUCCESS;
message.obj=response.body().string();
handler.sendMessage(message);
}
});
}
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==HTTTP_SUCCESS){
String obj = (String) msg.obj;
httpLisenter.success(obj);
}else {
httpLisenter.fail();
}
}
};
public void result(HttpLisenter httpLisenter){
this.httpLisenter=httpLisenter;
}
public interface HttpLisenter{
void success(String data);
void fail();
}
}
bean类
package com.bw.movie.bean;
public class Token {
private String access_token;
private String refresh_token;
private String openid;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
}