notes 1:jCenter Service will be shut down after May 1, 2021, WeChat SDK Migrated to Maven Central, ask developers to modify the reference repository in time.

notes 2: WeChat SDK Change to pass Gradle To the Maven Central, the package name has been modified accordingly, from the original com.tencent.mm.sdk Amend to read Com.tencent.mm.opensdk, requires developers to modify the corresponding import Statement.

notes This article is WeChat Android Tutorial for novice users of terminal development tools, involving only professors SDK The default reader is already familiar with GOES Basic usage of Android Studio (recommended) or Eclipse, and have a certain programming knowledge base.

# Update notes for open SDK 6.8.0

WeChat will be released in the near future targetSdkVersion The client version of 30,Due to the Android 11 system features, the WeChat version is available on Android When running on a device with system version 11 or above, functions such as authorized login, sharing, WeChat payment are affected and may not be used normallyIn order to adapt to the new version of Android system features, to ensure the normal use of WeChat functions, please third-party applicationsBy 1 November 2021To update,Click to see updated guidelines

# catalog

# Access Guide

# 1. Apply for your AppID

Please come Developer Application Registration Page Register, register and select the mobile app to set up, submit the app for audit, only approved applications can be developed.

# 2. Download SDK and API file

Android Studio Under the environment:

  • in build.gradle File, add the following dependencies:
dependencies {
    api 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
}

(wechat-sdk-android-with-mta is no longer maintained as of version 5.4.3)

  • Because jCenter Service shutdown, need to be modified to reference Maven Central, at the root of the project build.gradle File, add the following code:
buildscript {
    repositories {
        jcenter()       // original jCenter References can be retained
        mavenCentral()
    }
}

allprojects {
    repositories {
        jcenter()      // original jCenter References can be retained
        mavenCentral()
    }
}

Pay special attention to the present Maven Central only supports partial versions: 6.6.4, 6.6.5, 6.23, 6.7.0, 6.7.9, 6.8.0 Developers are advised to upgrade to the latest version 6.8.0. All subsequent updates will be uploaded to Maven Central。

Eclipse Under the environment:

Please proceed toResource Download Page SDK Bag.

# 3. Building the development environment

Android Studio Under the environment:

in Android Studio And ensure that the network settings can be successfully downloaded from the Maven Central Download WeChat SDK You can.

Eclipse Under the environment:

[1] in Eclipse Build your project in.

[2] Create a new one in the project libs In the development toolkit, the libs Directory libammsdk.jar To this directory, as shown in the figure below, a class named SDK_Sample The project and put jar Package replication to libs Directory).

[3] Right-click Project, select Build Path to hit the target Configure Build Path... Check. Libraries this Tab and pass the Add Jars... import project libs Directory libammsdk.jar File. (Shown below).

When you need to use the WeChat terminal API File to import the corresponding class.

import with.tencent.mm.opensdk.openapi.WXTextObject

# 4. Using the Development Kit in your code

[1] AndroidManifest.xml Set up

Add necessary permissions support where network permissions are not necessary if you do not use the scan code login featureThe last three permissions, if not used Mta, also unnecessary, even if used Mta, removed also does not affect the function):

<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"/>

[2] Register to WeChat

In order for your app to be able to respond to your app, you must register your app with the WeChat app in the code. id。 As shown in the figure below, you can use the Activity of onCreate Callback function, or other appropriate place your application id Register to WeChat. An example registration function is shown in the following figure.

	// APP_ID Replace with your app's legitimate app ID from the official website
private static final String APP_ID = "wx88888888"

// IWXAPI It's an open Api interface for third-party apps and WeChat communications.
private IWXAPI api

private regToWx() {
    // Get an instance of IWX API through the WX APIFactory factory
    api = WXAPIFactory.createWXAPI(this, APP_ID, true)

    // Register app appId to WeChat
    api.registerApp(APP_ID)

   //Suggest dynamic monitoring WeChat start broadcasting to register WeChat
  registerReceiver(new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {

     // Register the app to WeChat
    api.registerApp(Constants.APP_ID)
   }
  }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))

}

[3] Send request or response to WeChat

Now, your program can send a request or a response to a WeChat terminal by IWXAPI of sendReq and sendResp Two methods to achieve.

boolean sendReq(BaseReq req)

sendReq It's a third party. app Take the initiative to send a message to WeChat, after sending it will cut back to the third party app Interface.

boolean sendResp(BaseResp (resp)

sendResp Is WeChat to a third party app Request data, third party app Respond to the data and cut back to the WeChat interface.

sendReq As shown in the following figure:

//Initialize a WXTextObject Object to fill in the shared text
WXTextObject textObj = new WXTextObject()
textObj.text = text

//use WXTextObject Object initializes a WXMediaMessage object
WXMediaMessage msg = new WXMediaMessage()
msg.mediaObject = textObj
msg.description = text

SendMessageToWX.Req req = new SendMessageToWX.Req()
req.transaction = String.valueOf(System.currentTimeMillis())  //The transaction field identifies a request with a unique
req.message = msg
req.scene = mTargetScene

//Call api interface, send data to WeChat
api.sendReq(req)

Note that SendMessageToWX. Req of scene Member, if scene fill WX Scene Session, then the message will be sent to the WeChat session. if scene fill WXSceneTimeline (WeChat 4.2 Above support, com.tencent.mm . opensdk.constants.Build . java It defines the version number of each function support, if you need to check the WeChat version support API In the case of, Callable IWXAPI of getWXAppSupportAPI Method, for example, to judge whether WeChat supports sharing to the circle of friends function, can be judged as follows:

if (api.getWXAppSupportAPI() >= Build.TIMELINE_SUPPORTED_SDK_INT) {
    //of the share
}

Then the message will be sent to the circle of friends. scene Default value is WXSceneSession。

sendResp Implementation of SendReq Similarly, as shown below:

// Initialize a WXTextObject object
WXTextObject textObj = new WXTextObject()
textObj.text = text

// use WXTextObject Object initializes a WXMediaMessage object
WXMediaMessage msg = new WXMediaMessage(textObj)
msg.description = text

// Construct a Resp
GetMessageFromWX.Or or = new GetMessageFromWX.Or()
// Req transaction will be set to the resp object, where the bundle is the content of the intent delivered by WeChat, through getExtras() method acquisition
ortransaction = new GetMessageFromWX.Req(bundle).transaction
ormessage = msg

//Call api interface, send data to WeChat
api. sendResp ((resp) 

Specific content to be sent by a third party app Developer definition, specific reference WeChat development kit SDK Sample Demo Source code.

[4] Receive WeChat request and return value

If your application needs to receive a request sent by WeChat, or the result of a response sent to a WeChat request, it needs the following 3 Step operation:

a. Create a new directory under your package name wxapi Directory and in the wxapi Add a new one to the directory WXEntryActivity Class, which inherits from the Activity such as the package name of the application Net. Sourceforge. simcpux, the newly added class is shown below

And in manifest Add the export, taskAffinity, and launchMode attributes to the file, where export is set to true, tasksAfficity to your package name, and launch Mode to singleTask, for example:

<activity
    android:name=".wxapi.WXEntryActivity"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Translucent.NoTitleBar"
    android:exported="true"
    Android: taskAffinity = "fill in your bag name"
    android:launchMode="singleTask">
</activity>

b. Realization IWXAPIEventHandler The request sent by WeChat will be called back to onReq Method, the response result sent to the WeChat request will be called back to the onResp method

c. in WXEntryActivity Will receive intent And realized IWXAPIEventHandler Interface is passed to the IWXAPI Interface handleIntent Method, an example is shown below

api.handleIntent(getIntent(), this)


When WeChat sends a request to your app, it will be sent through IWXAPIEventHandler Interface onReq Method, similar to the application request WeChat response results will be passed through the onResp Callback.

Note

[1]If you need to obfuscate the code, to ensure sdk For normal use, you need to proguard.cfg Add the following two lines of configuration:

-keep class com.tencent.mm.opensdk.** {
    *
}

-keep class com.tencent.wxop.** {
    *
}

-keep class com.tencent.mm.sdk.** {
    *
}

[2]If you need to run SDK Sample Works by specifying debug.keystore To sign:

Android Studio Under the environment:

signingConfigs {
    debug {
        storeFile file("../debug.keystore")
    }
}

Eclipse Under the environment:

Please refer to the document <How to run it SDK Demo engineering

So far, you have been able to use WeChat Android Development kit API Content. If you want to know more about each API Function, see Android Platform reference manual Or download or read WeChat SDK Sample Demo Source code.

To download WeChat SDK sample code

# Android 11 - Update open SDK adaptations

Targeting WeChat targetSdkVersion The client version of 30,Due to the Android 11 system features, the WeChat version is available on Android When running on a device with system version 11 or above, functions such as authorized login, sharing, WeChat payment are affected and may not be used normallyIn order to adapt to the new version of Android system features, to ensure the normal use of WeChat functions, please third-party applicationsBy 1 November 2021Update below:

# Adaptation scheme

  1. Third party apps need to update WeChat Android SDK to version 6.8.0, quoting code as follows:
dependencies {
    api 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:6.8.0'
    // Or quote the latest version.
    // api 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
}

Whether third-party application targetSdkVersion upgrade to 30 or not, all need to WeChat Android SDK version upgrade adaptation.

  1. TargetSdkVersion upgrades to 30 third-party apps due to Android 11 Package visibility Effects of properties,The Open SDK interface may not be able to pull up WeChat, thus unable to use some functions of WeChatAndroidManifest.xml in the main project Add a tag to the following code:
<manifest package="com.example.app">

      ...

      // Add the following in the application's AndroidManifest.xml<queries>label
    <queries>
        <package android:name="com.tencent.mm" />   // Specify WeChat package name 
    </queries>

      ...

</manifest>

Note: After adding the above tags, developers need to upgrade the compiler tool, otherwise there will be compilation errors.

  • Android Studio NeedUpgrade to 3.3 And above, it is recommended to upgrade to 4.0 And above version
  • Android SDK Build-Tools NeedUpgrade to 30 And above version
  • with.android.tools.build:gradle Need to upgrade to 3.6.0 Version and above

# Validation process

  1. Environmental preparation:

  2. Validation process:

(1) After installing the third-party application, the first time to trigger the WeChat login function. (Note: Do not trigger any open SDK functions such as sharing, jumping, etc.)

(1) After installing the third-party application, the first time to trigger the WeChat login function. (Note: Do not trigger any open SDK functions such as sharing, jumping, etc.)

(2) If you successfully complete the WeChat login function, that is, verify the success of open SDK update.

(2) If signature verification fails and the callback errcode = -6 is received, the developer will have to recheck that steps 1 and 2 are complete.

TargetSdkVersion upgrade to 30 third-party applications, specific adaptation details can also refer to the documentAndroid 11 Update system policy, please developers timely adaptation