Android access wechat sharing

I. preparations

Wechat open platform account registration - > Wechat open platform

Create an application and fill in the application information as required (pay attention to the signature of the application package here. The appid obtained by using the signature of the debug package can only be used by the debug package, and the same is true for release)

Get the appID after passing the audit:

Two. Integration

1. Add dependency in build.gradle file

android{
    ...
    buildTypes{
        debug{
            minifyEnabled false
            buildConfigField "String", "WECHAT_APP_ID", '"Your wechat sharing appID"'
        }
    }
}

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

Add required permissions in Android manifest

<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. Register and share content through a tool class

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; //Send to friends or wechat friends;

        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);
            }
        }
    }

    /**
     * Pre inspection
     *
     * @param content
     * @return
     */
    private boolean hasPreHandleException(Object content) {
        if (null == content) {//Null pointer exception, the Object passed is null
            Looper.prepare();
            Toast.makeText(appcontext, R.string.wx_err_no_content, Toast.LENGTH_SHORT).show();
            Looper.loop();
            return true;
        }
        if (!api.isWXAppInstalled()) {//Wechat is not installed
            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();
    }

    /**
     * Share picture isTimeline send friend circle, true is friend circle, false is friend circle friend
     */
    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);  // set thumbnail 
        }

        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();
    }

    /**
     * Share links
     */
    public void shareUrlToWX(boolean isTimeline, String url, Bitmap thumbBmp, String title, String descroption) {
        //Initialize a WXWebpageObject and fill in the url
        WXWebpageObject webpageObject = new WXWebpageObject();
        webpageObject.webpageUrl = url;
        //Initialize a wxmediamassage with the WXWebpageObject object object
        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. Wechat callback

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();
    }
}

It should be noted that WXEntryActivity can only be named in this way. The path must be in the package name / wxapi folder!

Keywords: Android Gradle SDK

Added by ace_lovegrove on Thu, 14 Nov 2019 21:29:28 +0200