Android 接入微信分享

一、准备工作

微信开放平台注册账号 ->  微信开放平台

创建应用,按要求填写应用信息(这里注意应用包签名,用debug包签名得到的appid只能debug包使用,release同理)

通过审核后拿到appID:

二、集成

1、build.gradle文件中添加依赖

android{
    ...
    buildTypes{
        debug{
            minifyEnabled false
            buildConfigField "String", "WECHAT_APP_ID", '"你的微信分享appID"'
        }
    }
}

dependencies {
    api'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
}

AndroidManifext中添加需要的权限

<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2、通过一个工具类完成注册和分享内容的处理

public class WXShareManager {

    private static final String APP_ID = BuildConfig.WECHAT_APP_ID;

    private static final String SHARE_IMAGE_PATH = "0";
    private static final String SHARE_IMAGE_DATA = "1";

    private static WXShareManager manager;
    private static Context appcontext;

    public IWXAPI api;

    public WXShareManager(Context context) {
        appcontext = context;
        api = WXAPIFactory.createWXAPI(appcontext, APP_ID, true);
    }

    public static WXShareManager getInstance(Context context) {
        if (appcontext == null || !appcontext.equals(context) || manager == null) {
            appcontext = context;
            manager = new WXShareManager(context);
        }
        return manager;
    }

    private class WXShareThread extends Thread {

        private Object content;
        private String datatype;
        private boolean isTimeline; //发送到朋友圈还是微信好友;

        public WXShareThread(Object content, String datatype, boolean isTimeline) {
            this.content = content;
            this.datatype = datatype;
            this.isTimeline = isTimeline;
        }

        @Override
        public void run() {
            super.run();
            if (!hasPreHandleException(content)) {
                WXImageObject imgObj = null;
                Bitmap thumbBmp = null;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 4;
                switch (datatype) {
                    case SHARE_IMAGE_PATH:
                        imgObj = new WXImageObject();
                        imgObj.setImagePath((String) content);
                        thumbBmp = Bitmap.createScaledBitmap(
                                BitmapFactory.decodeFile((String) content, options), 150, 150, true);
                        break;
                    case SHARE_IMAGE_DATA:
                        imgObj = new WXImageObject();
                        imgObj.imageData = (byte[]) content;
                        thumbBmp = Bitmap.createScaledBitmap(BitmapFactory.decodeByteArray(
                                (byte[]) content, 0, imgObj.imageData.length), 100, 100, true);
                        break;
                }
                sharePictureToWX(imgObj, thumbBmp, isTimeline);
            }
        }
    }

    /**
     * 预先检查
     *
     * @param content
     * @return
     */
    private boolean hasPreHandleException(Object content) {
        if (null == content) {//空指针异常,传过来的Object是空
            Looper.prepare();
            Toast.makeText(appcontext, R.string.wx_err_no_content, Toast.LENGTH_SHORT).show();
            Looper.loop();
            return true;
        }
        if (!api.isWXAppInstalled()) {//微信没有安装
            Looper.prepare();
            Toast.makeText(appcontext, R.string.wx_err_no_install, Toast.LENGTH_SHORT).show();
            Looper.loop();
            return true;
        }
        return false;
    }

    public void sharePictureToWX(Object content, String datatype, boolean isTimeline) {
        new WXShareThread(content, datatype, isTimeline).start();
    }

    /**
     * 分享图片 isTimeline 是否发送朋友圈,true为朋友圈,false为朋友圈好友
     */
    public void sharePictureToWX(WXImageObject mediaObject, Bitmap thumbBmp, boolean isTimeline) {
        WXMediaMessage msg = new WXMediaMessage();
        if (mediaObject != null) {
            msg.mediaObject = mediaObject;
        } else {
            return;
        }
        if (thumbBmp != null) {
            msg.thumbData = ImageUtils.bmpToByteArray(thumbBmp, true);  // 设置缩略图
        }

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("imgshareappdata");
        req.message = msg;
        req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    /**
     * 分享链接
     */
    public void shareUrlToWX(boolean isTimeline, String url, Bitmap thumbBmp, String title, String descroption) {
        //初始化一个WXWebpageObject填写url
        WXWebpageObject webpageObject = new WXWebpageObject();
        webpageObject.webpageUrl = url;
        //用WXWebpageObject对象初始化一个WXMediaMessage
        WXMediaMessage msg = new WXMediaMessage(webpageObject);
        msg.title = title;
        msg.description = descroption;

        msg.setThumbImage(thumbBmp);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }
}
public static byte[] bmpToByteArray(Bitmap bmp, boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            recycleBitmap(bmp);
        }

        byte[] result = output.toByteArray();

        try {
            output.close();
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        return result;
}

3、微信回调

public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    private static final String TAG = "WXEntryActivity";

    private IWXAPI api;
    private static final String APP_ID = BuildConfig.WECHAT_APP_ID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);
        api.handleIntent(intent, this);
    }

   
    @Override
    public void onReq(BaseReq baseReq) {
        Log.v(TAG, "onReq: ");
        finish();
    }


    @Override
    public void onResp(BaseResp baseResp) {

        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                Toast.makeText(WXEntryActivity.this, R.string.wx_err_ok, Toast.LENGTH_LONG).show();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                Toast.makeText(WXEntryActivity.this, R.string.wx_err_auth_denied, Toast.LENGTH_LONG).show();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                Toast.makeText(WXEntryActivity.this, R.string.wx_err_user_cancel, Toast.LENGTH_LONG).show();
                break;
            default:
                Toast.makeText(WXEntryActivity.this, R.string.wx_err_unkown, Toast.LENGTH_LONG).show();
                break;
        }
        finish();
    }
}

需要注意的是,WXEntryActivity只能这么命名,路径一定要在 包名/wxapi 文件夹下!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KWMax

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值