Xamarin Android Binding Wechat SDK

Almost all APP s now integrate the functions of sharing with social platforms such as Weibo and Weixin. These social platforms officially provide SDK for developers to use. For Android and IOS platforms, only download the official SDK and integrate it according to the official instructions.

But for Xamarin, there is no official SDK, at this time we need to bind manually. First of all, from the Android layer, let's step by step realize how to integrate Wechat SDK in your own APP to realize sharing function.

1. On the official website of Weixin Open Platform https://open.weixin.qq.com/ Apply for a developer account, fill in the company's APP information, and pass the audit. The successful APPID will be used in the project. Then download the official Android_SDK Download address

2. Create a new Android binding library project

3. Place the Jar package in the downloaded official SDK in the Jars folder of the project

Remember to modify the attributes of the Jar package to the embedded Jar package, otherwise it will report errors when compiled in a real project.

4. Compiling at this time will result in errors, but don't be afraid that we will find the wrong place. It was the case that the compiler had a rename when it converted the Jar package into C# code. There are two ErrCodes in this class. This may be because the name of the original Java code attribute is errCode, and the compiler automatically capitalizes the first letter when converting to C# code, thus clashing with the subsequent ErrCode class.

 

5. When a rename appears, we can change his name. Open the project file Metadata.xml. This file is a configuration file when converting Jar package into C # code. It can remove classes, remove methods, modify field names and other operations. The specific functions of this file are not to mention in detail that interested friends can study Xamarin's official documents.

6. Add the following code, and the name will be changed to the name we specify when converting.

<metadata>
<!--
This sample removes the class: android.support.v4.content.AsyncTaskLoader.LoadTask:
<remove-node path="/api/package[@name='android.support.v4.content']/class[@name='AsyncTaskLoader.LoadTask']" />

This sample removes the method: android.support.v4.content.CursorLoader.loadInBackground:
<remove-node path="/api/package[@name='android.support.v4.content']/class[@name='CursorLoader']/method[@name='loadInBackground']" />
-->

<attr path="/api/package[@name='com.tencent.mm.opensdk.modelmsg']/class[@name='WXMediaMessage']/field[@name='mediaObject']" 
     name="managedName">MyMediaObject</attr>

<attr path="/api/package[@name='com.tencent.mm.opensdk.modelbase']/class[@name='BaseResp']/field[@name='errCode']" 
     name="managedName">MyErrCode</attr>
</metadata>

Compile again, OK has successfully generated Android's binding library. Next, build an Android project and try it out.

7. Add a reference to the Android binding library just now, and then modify the MainActivity.cs code

 

using Android.App;
using Android.Widget;
using Android.OS;
using Com.Tencent.MM.Opensdk.Openapi;
using Com.Tencent.MM.Opensdk.Modelbase;
using Com.Tencent.MM.Opensdk.Modelmsg;
using System;
using Android.Graphics;
using System.IO;

namespace WeChat.Android.Samples
{
    [Activity(Label = "WeChat.Android.Samples", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity, IWXAPIEventHandler
    {
        // IWXAPI It's a third party. app Communicating with Wechat openapi Interface
        private IWXAPI api;

        // APP_ID Replace legitimate applications for your application from official websites appId
        public const string APP_ID = "wxd930ea5d5a258f4f";

        //Minimum Support Friend Circle Version
        private const int TIMELINE_SUPPORTED_VERSION = 0x21020001;

        public void OnReq(BaseReq p0)
        {
            throw new NotImplementedException();
        }

        public void OnResp(BaseResp p0)
        {
            throw new NotImplementedException();
        }

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            // adopt WXAPIFactory Factory, Acquisition IWXAPI Examples
            api = WXAPIFactory.CreateWXAPI(this, APP_ID, false);

            Button btnRegister = FindViewById<Button>(Resource.Id.btnRegister);
            btnRegister.Click += BtnRegister_Click;
            Button btnText = FindViewById<Button>(Resource.Id.btnText);
            btnText.Click += BtnText_Click;
            Button btnHtml = FindViewById<Button>(Resource.Id.btnHtml);
            btnHtml.Click += BtnHtml_Click;
            Button btnOpenWeChat = FindViewById<Button>(Resource.Id.btnOpenWeChat);
            btnOpenWeChat.Click += BtnOpenWeChat_Click;
            Button btnIsMoments = FindViewById<Button>(Resource.Id.btnIsMoments);
            btnIsMoments.Click += BtnIsMoments_Click;
        }

        //Do you support the circle of friends?
        private void BtnIsMoments_Click(object sender, EventArgs e)
        {
            int wxSdkVersion = api.WXAppSupportAPI;
            if (wxSdkVersion >= TIMELINE_SUPPORTED_VERSION)
            {
                Toast.MakeText(this, "wxSdkVersion = " + wxSdkVersion + "\n Support", ToastLength.Long).Show();
            }
            else
            {
                Toast.MakeText(this, "wxSdkVersion = " + wxSdkVersion + "\n I won't support it", ToastLength.Long).Show();
            }
        }

        //Open the Wechat APP
        private void BtnOpenWeChat_Click(object sender, EventArgs e)
        {
            Toast.MakeText(this, "launch result = " + api.OpenWXApp(), ToastLength.Long).Show();
        }

        //Web Type Sharing
        private void BtnHtml_Click(object sender, EventArgs e)
        {
            WXWebpageObject webObj = new WXWebpageObject();
            webObj.WebpageUrl = "https://www.xamarin.com/";

            WXMediaMessage msg = new WXMediaMessage(webObj);
            msg.Title = "Xamarin Official website";
            msg.Description = "Description of official website";

            //Shared thumbnails
            Bitmap thumb = BitmapFactory.DecodeResource(this.Resources, Resource.Drawable.Icon);
            MemoryStream ms = new MemoryStream();
            thumb.Compress(Bitmap.CompressFormat.Png, 0, ms);
            byte[] bytes = ms.ToArray();

            //Construct a Req request
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            //Unique Request Flag
            req.Transaction = System.Guid.NewGuid().ToString();
            req.Message = msg;
            req.Scene = SendMessageToWX.Req.WXSceneTimeline;

            //send data
            api.SendReq(req);
        }

        //Text Type Sharing
        private void BtnText_Click(object sender, EventArgs e)
        {
            //Initialize a WXTextObject Object, Fill in Shared Text Content
            WXTextObject textObj = new WXTextObject();
            textObj.Text = "Hello Xamarin";

            //use WXTextObject Object initialization WXMediaMessage object
            WXMediaMessage msg = new WXMediaMessage();
            msg.MyMediaObject = textObj;
            msg.Description = "Hello World";

            //Construct a Req request
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            //Unique Request Flag
            req.Transaction = System.Guid.NewGuid().ToString();
            req.Message = msg;
            req.Scene = SendMessageToWX.Req.WXSceneSession;

            //send data
            api.SendReq(req);
        }

        // Will app Register to Wechat
        private void BtnRegister_Click(object sender, EventArgs e)
        {            
            var result = api.RegisterApp(APP_ID);
            Toast.MakeText(this, "Registration results:" + result, ToastLength.Short).Show();
        }
    }
}

Interface file Main.axml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/btnRegister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="take app Register to Wechat" />
    <Button
        android:id="@+id/btnText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send text" />
    <Button
        android:id="@+id/btnHtml"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send Web Pages" />
    <Button
        android:id="@+id/btnOpenWeChat"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Open the Wechat" />
    <Button
        android:id="@+id/btnIsMoments"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Do you support the circle of friends?" />
</LinearLayout>

8. Up to now, the work has been completed. Now let's debug it. If there is a flicker when sharing, you just need to change the APP_ID to the one you registered on the Wechat Open Platform.

Finally, attach Github source address: https://github.com/vilyo/WeChatDemo

Keywords: C# Android SDK xml github

Added by prkarpi on Wed, 12 Jun 2019 02:40:14 +0300