Android Wechat Sharing Problem Solving Carefully (2)

Posted by candice on Mon, 27 May 2019 21:59:28 +0200

Share audio clicks and jump pages to display a Black-screen player (there is nothing completely black on the page)

Later, when sharing audio, you need to add a URL address to share music, that is, the WXMusicObject.musicUrl attribute, but there's another place to go. When I set up a shared audio address, OK can share and play, but when I clicked on the shared content, I jumped to a page that didn't know what the ghost was. There were no all-black pages except the play and pause buttons. How depressed! Later, through multiple lookups, WX did not provide the attributes of the shared page in the WXMusicObject class. So it can only be spliced by itself through musicUrl attributes:

Sharing Address +" wechat_music_url="+Audio Address

Failure of Weichat Client's First Landing and Sharing

We thought we could share the data safely. The good test brought BUG to us. The first time that the Wechat client landed (cleared the WX data) was unsuccessful through the project. But depression was the second success. I don't know what Wechat is doing. Find a lot of documents without such a thing happened, but also test IOS sharing is not this problem, once thought it might be WX-SDK problem. Later, through Wechat Demo, it was found that the IWXAPI.register() registration method was invoked in each Activity. So this method is written in the Application, and I am satisfied that it should be no problem, but it has no effect through test revert, so all kinds of tests found that when the application is also in the Application, it fails to share in the WX client after opening the application. But when you log in, it's okay to start app sharing. So I adjusted the registration position and called the register () method every time I shared. unregister() method is called to cancel registration when sharing is completed. This problem was solved perfectly.

Here's a simple encapsulation of a tool class and a shared audio example.

public class WXShareUtils {
    private final String TAG = TTLog.makeLogTag(WXShareUtils.class);
    private int THUMB_SIZE = 150;
    private static volatile WXShareUtils manager;
    //Constructor object
    private Builder mBuilder;
    private IWXAPI api;

    private WXShareUtils() {
    }

    public static WXShareUtils getInstance() {
        WXShareUtils cache = manager;
        if (cache == null) {
            synchronized (WXShareUtils.class) {
                cache = manager;
                if (cache == null) {
                    cache = new WXShareUtils();
                    manager = cache;
                }
            }
        }
        return cache;
    }

    public void shareMusic() throws IllegalStateException {
        if (mBuilder == null) {
            TTLog.d(TAG, "The utility object is null. --->Builder is not null.<---");
            throw new IllegalStateException("The utility object is null. --->Builder is not null.<---");
        } else if (TextUtils.isEmpty(mBuilder.getMusicUrl())) {
            TTLog.d(TAG, "--->MusicUrl is not null.<---");
            throw new IllegalStateException("--->MusicUrl is not null.<---");
        } else if (mBuilder.getScene() != 0 && mBuilder.getScene() != 1) {
            TTLog.d(TAG, "--->scene is SendMessageToWX.Req.WXSceneTimeline(0) or SendMessageToWX.Req.WXSceneSession(1).<---");
            throw new IllegalStateException("--->scene is SendMessageToWX.Req.WXSceneTimeline(0) or SendMessageToWX.Req.WXSceneSession(1).<---");
        } else if (mBuilder.getActivity() == null) {
            TTLog.d(TAG, "--->Activity is not null.<---");
            throw new IllegalStateException("--->Activity is not null.<---");
        } else if (TextUtils.isEmpty(mBuilder.getTitle())) {
            TTLog.d(TAG, "--->Title is not null.<---");
            throw new IllegalStateException("--->Title is not null.<---");
        } else if (TextUtils.isEmpty(mBuilder.getDescription())) {
            TTLog.d(TAG, "--->Description is not null.<---");
            throw new IllegalStateException("--->Description is not null.<---");
        } else if (TextUtils.isEmpty(mBuilder.getShareUrl())) {
            TTLog.d(TAG, "--->Share Url is not null.<---");
            throw new IllegalStateException("--->Share Url is not null.<---");
        }
        RequestAsyncTask task = new RequestAsyncTask() {
            @Override
            public void callBack(Bitmap bitmap) {
                shareWXMusic(bitmap);
                releaseBuilder();
            }
        };
        task.execute(mBuilder.getImageUrl());
    }

    /**
     * Share audio
     *
     * @param bmp
     */
    private void shareWXMusic(Bitmap bmp) {
        api = getApi();
        api.registerApp(Constants.APP_ID);
        if (api.isWXAppInstalled()) {
            WXMusicObject music = new WXMusicObject();
            music.musicUrl = mBuilder.getShareUrl() + "#wechat_music_url=" + mBuilder.getMusicUrl();
//            music.musicUrl = mBuilder.getMusicUrl();
//            music.musicLowBandUrl = mBuilder.getMusicUrl();
//            music.musicDataUrl = mBuilder.getShareUrl();

            WXMediaMessage msg = new WXMediaMessage();
            msg.mediaObject = music;
            msg.title = mBuilder.getTitle();
            msg.description = mBuilder.getDescription();

            Bitmap thumbBmp = null;
            if (bmp != null) {
                thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                msg.thumbData = bmpToByteArray(thumbBmp, true);
                bmp.recycle();
            } else {
                Bitmap resBitmap = BitmapFactory.decodeResource(TTApplication.getAppResources(), R.drawable.share_default_icon);
                thumbBmp = Bitmap.createScaledBitmap(resBitmap, THUMB_SIZE, THUMB_SIZE, true);
                msg.thumbData = bmpToByteArray(thumbBmp, true);
                resBitmap.recycle();
            }
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("music");
            req.message = msg;
            req.scene = mBuilder.getScene();
            api.sendReq(req);
        } else {
            ToastUtils.showToast(mBuilder.getActivity(), R.string.share_error_content);
        }
        api.unregisterApp();
    }

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

    private byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, output);
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (needRecycle) {
            bmp.recycle();
        }
        return result;
    }


    private Bitmap getImageFromNet(String url) {
        HttpURLConnection conn = null;
        try {
            URL mURL = new URL(url);
            conn = (HttpURLConnection) mURL.openConnection();
            conn.setRequestMethod("GET"); //Setting Request Method
            conn.setConnectTimeout(10000); //Setting connection server timeout
            conn.setReadTimeout(5000);  //Setting read data timeout
            conn.setDoInput(true);
            conn.connect(); //Start connecting

            int responseCode = conn.getResponseCode(); //Get the server's response code
            if (responseCode == 200) {
                //Successful visit
                InputStream is = conn.getInputStream(); //Get the stream data returned by the server
                BufferedInputStream bufferedInputStream = new BufferedInputStream(is);
                Bitmap bmpImage = BitmapFactory.decodeStream(bufferedInputStream);//Create a bitmap object from stream data
                return bmpImage;

            } else {
                //Access failed
                TTLog.d(TAG, "Access failed===responseCode: " + responseCode);
            }
        } catch (Exception e) {
            TTLog.e(TAG, e, "load image url fail");
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect(); //Disconnect
            }
        }
        return null;
    }

    /**
     * Asynchronous loading of pictures
     */
    private abstract class RequestAsyncTask extends AsyncTask<String, Void, Bitmap> {
        public abstract void callBack(Bitmap bitmap);

        @Override
        protected Bitmap doInBackground(String... params) {
            if (TextUtils.isEmpty(params[0])) {
                return null;
            }
            return getImageFromNet(params[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            callBack(bitmap);
        }
    }

    /*
    * Internal Builder Builder Builder
    * */
    public static class Builder {
        private String musicUrl = null;
        private String title = null;
        private String description = null;
        private String imageUrl = null;
        private int scene = -1;//0 Friends 1 Friends Circle 2 Collection
        private Activity activity = null;
        private String shareUrl = null;

        public String getMusicUrl() {
            return musicUrl;
        }

        public Builder setMusicUrl(String musicUrl) {
            this.musicUrl = musicUrl;
            return this;
        }

        public String getTitle() {
            return title;
        }

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }

        public String getDescription() {
            return description;
        }

        public Builder setDescription(String description) {
            this.description = description;
            return this;
        }

        public String getImageUrl() {
            return imageUrl;
        }

        public Builder setImageUrl(String imageUrl) {
            this.imageUrl = imageUrl;
            return this;
        }

        public int getScene() {
            return scene;
        }

        /**
         * 0 Friends 1 Friends Circle
         *
         * @param scene
         * @return
         */
        public Builder setScene(int scene) {
            this.scene = scene;
            return this;
        }

        public Activity getActivity() {
            return activity;
        }

        public Builder setActivity(Activity activity) {
            this.activity = activity;
            return this;
        }

        public String getShareUrl() {
            return shareUrl;
        }

        public Builder setShareUrl(String shareUrl) {
            this.shareUrl = shareUrl;
            return this;
        }
    }

    private IWXAPI getIWXAPI() {
        return WXAPIFactory.createWXAPI(mBuilder.getActivity(), Constants.APP_ID, false);
    }

    private IWXAPI getIWXAPI(Context context){
        return WXAPIFactory.createWXAPI(context, Constants.APP_ID, false);
    }

    public IWXAPI getApi() {
        if (api != null)
            return api;
        else
            return getIWXAPI();
    }
    public IWXAPI getApi(Context context) {
        if (api != null)
            return api;
        else
            return getIWXAPI(context);
    }

    private void releaseBuilder() {
        if (mBuilder != null) {
            mBuilder = null;
            TTLog.d(TAG, "release WXShareUtils Builder.");
        }
    }

    /**
     * Configuration method
     *
     * @param builder
     * @return
     */
    public WXShareUtils option(Builder builder) {
        this.mBuilder = builder;
        return manager;
    }
}


Topics: Attribute iOS SDK