API Documentation

Last updated: 2020-03-25 09:42:13

PDF

All API's package names are prefixed with: com.tencent.android.tpush There are several important class names for providing interfaces, as shown in the following table

Class name Description
XGPushManager Push service push
XGPushConfig Push service configuration item interface
XGPushBaseReceive Receiver, that receives messages and result feedback requires developers to independently complete static registration in AndroidManifest.xml.

Launch and Registration

  • App can provide Push service on Tencent Mobile push SDK only after completing Launch and registration of Tencent Mobile push. Before that, make sure to configure AccessId and AccessKey.
  • The new version of SDK has integrated Launch Tencent mobile push and App registration into the registration API, that is, Launch and registration operations are completed by default by calling the registration API.
  • After successful registration, Device Token,Token will be returned to identify the uniqueness of Device, and it is also the only identity used by Tencent Mobile push to maintain a connection with Backend Background. For information on how to obtain Token, please refer to [Get Token](#Get Token) .

Registration interfaces are usually provided with simplified version and callback version. Please choose the interface according to your business needs.

Device registration

Interface description

General registration only registers the current Device, Backend Background can send push messages for different Device Token, there are 2 versions of API.

public static void registerPush(Context context)

This registration method does not support pushing accounts.

Parameter description

Context: current application context object, cannot be null.

Sample code

XGPushManager.registerPush(getApplicationContext());

Interface description

In order to facilitate users to obtain the status of whether the registration is successful or not, a version with callback is provided.

public static void registerPush(Context context,
final XGIOperateCallback callback)

Parameter description

  • Context: current application context object, cannot be null.
  • The callback:callback call, which mainly includes callbacks for success and failure of the operation, cannot be null.

Sample code

XGPushManager.registerPush(this, new XGIOperateCallback() {
@Override
public void onSuccess(Object data, int flag) {
Log.d("TPush", "The registration is successful, the device token is: " + data);
}
@Override
public void onFail(Object data, int errCode, String msg) {
Log.d("TPush", "The registration failed, error code: " + errCode + ",error message:" + msg);
}
})

Bind account registration

Interface description

Register App, with the specified account so that you can send push messages to the specified account through Backend Background. There are 2 versions of API.

Launch and register for the app, and at the same time bind the account. Recommended for apps with an account system. This API will override accounts previously bound to the device, and only the current registered account will take effect
void bindAccount(Context context, String account, XGIOperateCallback callback)

Launch and register for the app, and at the same time bind the account. Recommended for apps with an account system. This API will override accounts previously bound to the device, and only the current registered account will take effect. There is no registration callback    
void bindAccount(Context context, final String account)

Launch and register for the app, and at the same time bind the account. Recommended for apps with an account system. This API will retain the previous account and only perform an addition operation. One token can have a maximum of 10 accounts, otherwise accounts that are bound previously will be automatically replaced. There is registration callback
void appendAccount(Context context, String account, XGIOperateCallback callback)

Launch and register for the app, and at the same time bind the account. Recommended for apps with an account system. This API will retain the previous account and only perform an addition operation. One token can have a maximum of 10 accounts, otherwise accounts that are bound previously will be automatically replaced. There is no registration callback
void appendAccount(Context context, final String account)        
  • The account here can be any kind of business account, such as email, mobile phone number, user name and so on.
  • When multiple Device are bound to the same account, Backend Background will push the message to the last bound Device by default. If you need to push all the bound Device, you can see Rest API Account_push_type parameter settings in the document.

Parameter description

  • Context: current application context object, cannot be null.
  • Account: account.

Sample code

XGPushManager.bindAccount(getApplicationContext(),"test");

Account Unbind

Interface description

Unbind the bound account.

//Unbind the specified account (there is registration callback)

void delAccount(Context context, final String account, XGIOperateCallback callback)    

//Unbind the specified account (there is no registration callback)

void delAccount(Context context, final String account )

The account Unbind is only Associate who removes the Token and App accounts. If you use full / tag / Token push, you can still receive notifications / messages.

Parameter description

  • Context: current application context object, cannot be null.
  • Account: account.

Sample code

XGPushManager.delAccount(getApplicationContext(),"test");

Get the registration result

There are two ways to check whether the registration succeeds.

Use the registration interface of the Callback version .
The XGIOperateCallback class provides an API for handling successful or failed registration. Please refer to the example in the registration API.

Sample code

/**
* Operation callback API
*/
public interface XGIOperateCallback {
/**
* Operation callback API
* @param data Business data of a successful operation, such as the token information when registration is successful
* @param flag Flag tag
*/
public void onSuccess(Object data, int flag);
/**
* Callback when the operation fails
* @param data Business data of a failed operation
* @param errCode Error code
* @param msg Error message    
*/
public void onFail(Object data, int errCode, String msg);
}

Overload XGPushBaseReceiver
It can be obtained by overloading the onRegisterResult method of XGPushBaseReceiver.

The overloaded XGPushBaseReceiver needs to be configured in AndroidManifest.xml,. Please refer to the following [Message configuration](#Message configuration) .

Sample code

/**
* Registration result
*
* @param context
* App context object
* @param errorCode
* Error code; {@link XGPushBaseReceiver#SUCCESS} indicates success, while others indicate failure
* @param registerMessage
* Registration result return
*/

Class method list

Method name Return value Default Value Description
GetToken () String None Device's Token, is Device's unique identification ID.
GetAccessId () Long * 2018-5-4 Get registered AccessId
GetAccount String None Get the account that is registered and bound
GetTicket () String None Registered bill
GetTicketType () Short * 2018-5-4 Bill type

Anti-registration

Interface description

When the user has exited or the App is closed, and it is no longer necessary to receive the push, the App, can be unregistered, that is, the anti-registration. (once Device counter-registers, until the successful re-registration of Device, the message of deliver will not be received by Device.)

public static void unregisterPush(Context context)

Parameter description

The context object of the context: App.

Sample code

XGPushManager.unregisterPush(this);

Anti-registration result

It can be obtained by overloading the onUnregisterResult method of XGPushBaseReceiver.

  • The unregistration operation should not be too frequent; otherwise, it may cause backend synchronization delay.
  • There is no need for anti-registration to switch accounts. Multiple registrations will automatically be subject to the last time.

Sample code

<pre class="brush:cpp;">/**
* Unregistration result
*
* @param context
* App context object
* @param errorCode
* Error code; {@link XGPushBaseReceiver#SUCCESS} indicates success, while others indicate failure
*/
@Override
public void onUnregisterResult(Context context, int errorCode) {

}
</pre>

Notifications and messages

Tencent Mobile push service mainly provides two push formats: push notification and intra-application message command, which are different from each other.

Push notification (displayed in the notification bar)

It refers to the content displayed in Device's notification bar. Tencent Mobile pushes SDK to complete all operations. App can monitor the opening of notifications, that is, notifications from deliver at the foreground are displayed by default in the notification bar without any processing by App.

  • After successfully registering for Tencent mobile push service, deliver can notify you without any settings.
  • In general, combined with custom notification styles, regular notifications can meet most business needs. If you need a more flexible approach, consider using messages.

Intra-application message command (messages are not displayed in the notification bar)

It refers to the content sent to App by Tencent Mobile push. App needs to inherit the implementation of XGPushBaseReceiver API and handle all operations independently. In other words, deliver's message is not displayed in the notification bar by default. Tencent Mobile push is only responsible for the process of transferring messages from Tencent Mobile push server deliver to App. It is not responsible for message processing logic and needs to be implemented by App itself.

  • The message refers to the text message sent by the developer through the foreground or Backend Background script deliver. Tencent Mobile push is only responsible for delivering the message to App,App and is completely responsible for the processing of the message body.
  • Messages are highly flexible and highly customized, so they are more suitable for App to handle personalized business needs independently, such as deliver App configuration information, custom message storage and display, and so on.

Message configuration

Inherit XGPushBaseReceiver yourself and configure the following in the configuration file:

Sample code

<receiver android:name="com.tencent.android.xg.cloud.demo.MessageReceiver">
            <intent-filter>
                <!-- Receiving message pass through -->
                <action android:name="com.tencent.android.xg.vip.action.PUSH_MESSAGE" />
                <!-- Monitor the processing results of registration, anti-registration, setting / deleting tags, notification being clicked, etc -->
                <action android:name="com.tencent.android.xg.vip.action.FEEDBACK" />
            </intent-filter>
        </receiver>

Get intra-application messages

Developers need to inherit the XGPushBaseReceiver overloaded onTextMessage method to receive the developer's deliver message in the foreground. After receiving the message successfully, it will be processed according to the specific business scenario.

Please make sure that you have registered the receiver, that is YOUR_PACKAGE.XGPushBaseReceiver in AndroidManifest.xml.

public void onTextMessage(Context context,
XGPushTextMessage message)

Parameter description

  • context: The current context of the app.
  • Message: received the message structure.

Class method list

Method name Return value Default Value Description
GetContent () String None For the content of the message body, you usually only need deliver's field.
GetCustomContent () String None Message Custom key-value
GetTitle () String None Message title (the description in the message word in deliver's application from the foreground does not belong to the title)

Local notification

Local notification is customized by the user and retained locally. When the application is opened, Tencent Mobile push Service will determine whether there is a notification (once every 5 minutes) based on the network heartbeat. Local notifications need to be enabled by Service to pop up, and there may be a delay of about 5 minutes. (notice pop-up when the set time is less than the current Device time)

Sample code

        // Create a local notification
        XGLocalMessage local_msg = new XGLocalMessage();

        // Set the local message type; 1: notification, 2: message

        local_msg.setType(1);

        // Set the message title

        local_msg.setTitle("qq");

        // Set the message content

        local_msg.setContent("ww");

        // Set the message date in the format of 20140502, for example

        local_msg.setDate("20140930");

        // Set the hour when the message is triggered (in 24-hour time), for example: 22 indicates 10 p.m.

        local_msg.setHour("19");

        // Set the minute when the message is triggered, for example: 05 indicates the 5th minute in the hour

        local_msg.setMin("31");

        // Set the message style, the default value is 0 or none

        local_msg.setBuilderId(0);

        // Set the action type: 1 - open the activity or the app itself; 2 - open the browser; 3 - open the Intent; 4 - open the app by the package name

        local_msg.setAction_type(1);

        // Set the app-pulling page

        local_msg.setActivity("com.qq.xgdemo.SettingActivity");
        // Set the URL

         local_msg.setUrl("http://www.baidu.com");

        // Set the Intent

         local_msg.setIntent("intent:10086#Intent;scheme=tel;action=android.intent.action.DIAL;S.key=value;end");

        //Whether to overwrite the save settings of the original build_id. 1: Yes; 0: No.

         local_msg.setStyle_id(1);

        // Set the audio resource

         local_msg.setRing_raw("mm");

        // Set the key and value

         HashMap<String, Object> map = new HashMap<String, Object>();

         map.put("key", "v1");

          map.put("key2", "v2");

        local_msg.setCustomContent(map);

        // Set the URL for downloading apps

        local_msg.setPackageDownloadUrl("http://softfile.3g.qq.com:8080/msoft/179/1105/10753/MobileQQ1.0(Android)_Build0198.apk");

        // Add notification locally
        XGPushManager.addLocalNotification(context,local_msg);

Get Device Token

Token is the only identity for Tencent Mobile push to maintain a connection with the backend leader, and it is the only ID, for App to receive messages. Only after Device registers successfully can Token, be obtained by the following methods. (the Token pushed by Tencent Mobile may change when it is reinstalled by Unmount. )

Obtain through the registration API with callback

In the onSuccess (Object data, int flag) method of the registration API with XGIOperateCallback, the parameter data is the relevant example that Token, can refer to the registration API.

Overload XGPushBaseReceiver

Overload the onRegisterResult (Context context, int errorCode, XGPushRegisterResult registerMessage) method of XGPushBaseReceiver and obtain it through the getToken API provided by parameter registerMessage. For more information, please see "getting Registration result" section.

XGPushConfig.getToken (context)

Once Device registers successfully, he will store the Token locally, which can then be obtained through the XGPushConfig.getToken (context) API.

Get notification

Interface description

Deliver and display of notifications are completely controlled by Tencent Mobile push SDK, but some developers need to store displayed notification content locally, which can be achieved by overloading the onNotificationShowedResult (Context, XGPushShowedResult) method of XGPushBaseReceiver. Where the XGPushShowedResult object provides an interface to read the contents of the notification.

public abstract void onNotificationShowedResult(Context context,XGPushShowedResult notifiShowedRlt); 

Parameter description

  • Context: current application context.
  • The notification object to which the notifiShowedRlt: is displayed.

Get message click result

Notification effect monitoring and custom key-value

Use the built-in activity display page of Tencent Mobile push SDK to count the arrival of notifications / messages, clicks and clearances of notifications by default. However, if you want to listen to these events, you need to embed the code as follows.

To count the opening App operations caused by Tencent Mobile push or to obtain deliver's custom key-value, developers need to call the following method on all (or opened) Activity onResume ().

Interface description

onNotificationClickedResult(Context context, XGPushClickedResult notifiClickedRlt); 

Sample code

/ / Notification Click callback actionType=1 for the message is cleared, actionType=0 for the message is clicked 
 @Override 
 Public void onNotificationClickedResult (Context context, 
 XGPushClickedResult message) { 
 If (context = = null | | message = = null) { 
 return; 
 } 
 String text = ""; 
 If (message.getActionType ()) = = NotificationAction.clicked.getType ()) { 
 / / Notification is clicked on the notification bar 
 / / APP handles the actions related to clicks by itself. 
 Text = "Notification opened:" + message; 
 } else if (message.getActionType () = = NotificationAction.delete.getType ()) { 
 / / Notification is cleared 
 / / APP handles the relevant actions after the notification is cleared by itself 
 Text = "Notification cleared:" + message;
}
Toast.makeText (context, "broadcast received notification is clicked:" + message.toString (), 
 Toast.LENGTH_SHORT). Show (); 
 / / obtain custom key-value 
 String customContent = message.getCustomContent (); 
 If (customContent! = null & & customContent.length ()! = 0) { 
 try { 
 JSONObject obj = new JSONObject (customContent); 
 / / key1 is the key configured in the foreground 
 If (! obj.isNull ("key")) { 
 String value = obj.getString ("key"); 
 Log.d (LogTag, "get custom value:" + value); 
 } 
 / /. 
 } catch (JSONException e) { 
 e.printStackTrace(); 
 } 
 } 
 / / the process of autonomous processing by APP.
Log.d(LogTag, text);
show(context, text);
}

Parameter description

The activity: is opened in the activity context.

Return value

XGPushClickedResult: notifies the opened object. If the activity is caused by the notification pushed by Tencent Mobile, return XGPushClickedResult, otherwise return null.

Class method list

Method name Return value Default Value Description
GetMsgId () Long * 2018-5-4 Message ID
GetTitle () String None Notification title
GetContent () String None The content of the body of the notice
GetActivityName () String None Name of the page that was opened
GetCustomContent () String None To customize the key-value,JSON string, at the same time, call the following method in the onPause () of Activity

Tags

Preset label

Currently, Tencent Mobile push offers two types of preset tags:

  • Geographic location (at the provincial level).
  • App version number.
  • Preset tags are automatically reported within SDK.

Set custom label

Interface description

You can set tags for different users and then send mass notifications based on tag names in the frontend. An application has a maximum of 10000 tag, and each Token is not allowed to contain spaces in a maximum of 100 tag, tag in an application.

public static void setTag(Context context, String tagName) 

Parameter description

  • Context:Context object
  • The name of the label to be set by tagName: cannot be null or empty.

Result

It can be obtained by overloading the onSetTagResult method of XGPushBaseReceiver.

Sample code

XGPushManager.setTag(this, "male"); 

Set multiple tags

Interface description

Setting more than one tag at a time will overwrite the tag previously set by Device.

public static void setTags(Context context, String operateName, Set<String> tags) 

Parameter description

  • Context:Context object.
  • The name of the operateName: user-defined operation, and the callback result will be returned as is to identify which operation the callback belongs to.
  • A collection of tags: tag signatures, each of which is a String. Limit: each tag cannot exceed 40 bytes (more than will be discarded) and cannot contain spaces (spaces will be deleted if spaces are included). A maximum of 1000 tag, will be discarded.

Result

It can be obtained by overloading the onSetTagResult method of XGPushBaseReceiver.

Sample code

String[] tags = "tag1 tag2".split(" ");
Set<String> tagsSet = new HashSet<>(Arrays.asList(tags));
XGPushManager.setTags(getApplicationContext(), "setTags:" + System.currentTimeMillis(), tagsSet); 

Add multiple tags

Interface description

Setting more than one tag at a time will overwrite the tag previously set by Device.

  • If the format of the new tag is "test:2 level:2", all Device's history tags will be deleted, and test:2 and level will be added.
  • If some of the new tags do not have a: sign, such as "test:2 level", all Device's history tags will be deleted, and test:2 and level tags will be added.
  • In the new tags, the: number is the Backend Background keyword. Please use it according to the specific business scenario.
  • This API needs to be called for a period of time (it is recommended to be greater than 5s), otherwise the update may fail.
public static void addTags(Context context, String operateName, Set<String> tags) 

Parameter description

  • Context:Context object.
  • The name of the operateName: user-defined operation, and the callback result will be returned as is to identify which operation the callback belongs to.
  • A collection of tags: tag signatures, each of which is a String. Limit: each tag cannot exceed 40 bytes (more than will be discarded) and cannot contain spaces (spaces will be deleted if spaces are included). A maximum of 1000 tag, will be discarded.

Result

It can be obtained by overloading the onSetTagResult method of XGPushBaseReceiver.

Sample code

String[] tags = "tag1 tag2".split(" ");
Set<String> tagsSet = new HashSet<>(Arrays.asList(tags));
XGPushManager.addTags(getApplicationContext(), "addTags:" + System.currentTimeMillis(), tagsSet);

Deleting Tags

Interface description

This is to delete user tag data.

public static void deleteTag(Context context, String tagName) 

Parameter description

  • Context:Context object.
  • The name of the label to be set by tagName: cannot be null or empty.

Result

It can be obtained by overloading the onDeleteTagResult method of XGPushBaseReceiver.

Sample code

XGPushManager.deleteTag (this, "male"); 

Delete multiple tags

Interface description

Delete multiple tags at one time.

public static void deleteTags(Context context, String operateName, Set<String> tags)

Parameter description

  • Context:Context object.
  • The name of the operateName: user-defined operation, and the callback result will be returned as is to identify which operation the callback belongs to.
  • A collection of tags: tag signatures, each of which is a String. Limit: each tag cannot exceed 40 bytes (more than will be discarded) and cannot contain spaces (spaces will be deleted if spaces are included). Up to 1,000 tags can be set, and excessive ones will be discarded.

Result

It can be obtained by overloading the onSetTagResult method of XGPushBaseReceiver.

Sample code

String[] tags = "tag1 tag2".split(" ");
Set<String> tagsSet = new HashSet<>(Arrays.asList(tags));
XGPushManager.deleteTags(getApplicationContext(), "deleteTags:" + System.currentTimeMillis(), tagsSet);

Clear all tags

Interface description

Clear all tags of this device.

public static void cleanTags(Context context, String operateName)

Parameter description

  • Context:Context object.
  • The name of the operateName: user-defined operation, and the callback result will be returned as is to identify which operation the callback belongs to.

Result

It can be obtained by overloading the onSetTagResult method of XGPushBaseReceiver.

Sample code

XGPushManager.cleanTags(getApplicationContext(), "cleanTags:" + System.currentTimeMillis());

Configure Interfac

All configuration-related APIs are in the XGPushConfig class. In order to make the configuration take effect in time, developers need to ensure that the configuration APIs are called before Launch or register for Tencent Mobile push.

Debug model

Interface description

To ensure the security of the data, make sure that the Debug mode is turned off when publish.

public static void enableDebug(Context context, boolean debugMode)

Parameter description

  • Context:App context object.
  • DebugMode: defaults to false. If you want to turn on Debug logging, set it to true.

Get Token

Interface description

Token is an identification ID, of Device randomly generated by the server according to Device attributes and deliver to the local. The Token of the same App is different on different Device.

public static String getToken(Context context)

The first registration of App will generate a Token, that will always be stored on the mobile phone. Regardless of the later unregistration operation, the Token will always exist. When the App is completely Unmount and Reinstall, the Token will change. The Token is different between different App.

Parameter description

Context:App context object.

Return value

Return normal Token; on success. Return null or 0 on failure.

Obtain the third party Vendor Token

Interface description

The third party Vendor Token is Vendor Device's identification ID, from Vendor deliver to the local. The Token of the same App is different on different Device.

public static String getOtherPushToken(Context context) 

It needs to be successfully registered before it can be called, otherwise it will be returned as NULL.

Parameter description

Context:App context object.

Return value

Return normal Token; on success. Return null or 0 on failure.

Setting AccessID

Interface description

If it has been configured in AndroidManifest.xml, you do not need to call it again; if both exist, this API shall prevail.

public static boolean setAccessId(Context context, long accessId)

Parameter description

  • Context: object.
  • The accessId registered at the accessId: front desk.

Return value

  • true: Success.
  • false: Failure.

The accessId set through this API will be stored in the file at the same time.

Setting AccessKey

Interface description

If it has been configured in AndroidManifest.xml, you do not need to call it again; if both exist, this API shall prevail.

public static boolean accessKey(Context context, String accessKey) 

Parameter description

  • Context: object.
  • The accesskey registered at the accessKey: front desk.

Return value

  • true: Success.
  • false: Failure.

The accessKey set through this API will be stored in the file at the same time.

New log reporting API

Interface description

If developers find that TPush-related functions are abnormal, they can call this API to trigger the reporting of local Push logs. When feedback is made, please give us the file address so that we can troubleshoot the problem.

public static void uploadLogFile(Context context, HttpRequestCallback httpRequestCallback)

Parameter description

  • Context:Context object, cannot be null.
  • HttpRequestCallback: upload log result callback, which mainly includes operation success and failure, and cannot be null.

Sample code

    XGPushManager.uploadLogFile(context, new HttpRequestCallback() {
        @Override
        public void onSuccess(String result) {
                Log.d ("TPush", "uploaded successfully", file address: "+ result);"
        }

        @Override
        public void onFailure(int errCode, String errMsg) {
                Log.d ("TPush", "upload failed, error code:" + errCode + ", error message:" + errMsg); "
        }
    });

First of all, you need to open it. XGPushConfig.enableDebug(this, true); .