com.tencent.android.tpush
. The following table lists important classes that provide APIs for external use.Class | Description |
XGPushManager | Push service |
XGPushConfig | Push service configuration item API |
XGPushBaseReceiver | Receiver to receive messages and result feedback, which needs to be statically registered by yourself in AndroidManifest.xml |
AccessId
and AccessKey
have already been configured.public static void registerPush(Context context)
context
: Context object of the current application, which cannot be null
XGPushManager.registerPush(getApplicationContext());
public static void registerPush(Context context,final XGIOperateCallback callback)
context
: Context object of the current application, which cannot be null
callback
: Callback functions, including success and failure callbacks and cannot be null
XGPushManager.registerPush(this, new XGIOperateCallback() {@Overridepublic void onSuccess(Object data, int flag) {Log.d("TPush", "Registration succeeded. Device token: " + data);}@Overridepublic void onFail(Object data, int errCode, String msg) {Log.d("TPush", "Registration failed. Error code: " + errCode + "; error message: " + msg);}})
XGIOperateCallback
class provides an API to process registration success or failure. Please see the sample in the registration API./*** Operation callback API*/public interface XGIOperateCallback {/*** Callback when the operation is successful* @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);}
onRegisterResult
method of XGPushBaseReceiver
.XGPushBaseReceiver
subclass needs to be configured in AndroidManifest.xml
. For more information, see Message configuration below./**** @param context //Current context* @param errorCode //`0` indicates success, while other values are error codes* @param message //Returned registration result*/@Overridepublic void onRegisterResult(Context context, int errorCode, XGPushRegisterResult message) {if (context == null || message == null) {return;}String text = "";if (errorCode == XGPushBaseReceiver.SUCCESS) { // Registration succeeded// Get the token hereString token = message.getToken();text = "Registration succeeded. Token:" + token;} else {text = message + "Registration failed. Error code:" + errorCode;}Log.d(LogTag, text);}
Method | Returned Value | Default Value | Description |
getToken() | String | None | Device token, i.e., unique device ID |
getAccessId() | long | 0 | Gets AccessId for registration |
getAccount | String | None | Gets the account bound for registration |
getTicket() | String | None | Login state ticket |
getTicketType() | short | 0 | Ticket type |
public static void unregisterPush(Context context)
context
: Context object of the applicationXGPushManager.unregisterPush(getApplicationContext(), new XGIOperateCallback() {@Overridepublic void onSuccess(Object data, int i) {Log.d("TPush", "Unregistration succeeded");}@Overridepublic void onFail(Object data, int errCode, String msg) {Log.d("TPush", "Unregistration failed. Error code: " + errCode + ", error message: " + msg);}});
onUnregisterResult
method of XGPushBaseReceiver
./*** Unregistration result* @param context //Current context* @param errorCode //0 indicates success, while other values are error codes*/@Overridepublic void onUnregisterResult(Context context, int errorCode) {if (context == null) {return;}String text = "";if (errorCode == XGPushBaseReceiver.SUCCESS) {text = "Unregistration succeeded";} else {text = "Unregistration failed" + errorCode;}Log.d(LogTag, text);}
onNotificationShowedResult(Context, XGPushShowedResult)
method of XGPushBaseReceiver
. Here, the XGPushShowedResult
object provides an API for reading notification content.onNotificationShowedResult
provided in the Tencent Push Notification Service SDK supports listening for the arrival of notifications delivered only through the Tencent Push Notification Service channel, but not through vendor channels.public abstract void onNotificationShowedResult(Context context,XGPushShowedResult notifiShowedRlt);
context
: Context of current applicationnotifiShowedRlt
: arrived notification objectonNotificationClickedResult(Context, XGPushClickedResult)
method of XGPushBaseReceiver.public abstract void onNotificationClickedResult(Context context, XGPushClickedResult notifiClickedRlt);
// If `actionType` of the notification click callback is `0`, the message was clicked; if it is `2`, the message was cleared@Overridepublic void onNotificationClickedResult(Context context, XGPushClickedResult message) {if (context == null || message == null) {return;}String text = "";if (message.getActionType() == NotificationAction.clicked.getType()) {// The notification is clicked on the notification bar// The application handles actions related to the clicktext = "notification opened:" + message;} else if (message.getActionType() == NotificationAction.delete.getType()) {// Notification is cleared// The application handles related actions after the notification is clearedtext = "notification cleared:" + message;}// Handling process of the applicationLog.d(LogTag, "broadcast that the notification is received:" + text);}
context
: Context of current applicationXGPushClickedResult
: Opened object of the notificationXGPushClickedResult
class are as follows:Method | Returned Value | Default Value | Description |
getMsgId() | long | 0 | Message ID |
getTitle() | String | None | Notification title |
getContent() | String | None | Notification body content |
getActionType() | String | None | 0: The notification is clicked; 2: The notification is cleared |
getPushChannel() | String | 100 | ID of the channel through which the clicked notification is delivered 100: Tencent Push Notification Service channel 101: FCM channel 102: Huawei channel 103: Mi channel 104: vivo channel 105: OPPO channel 106: Meizu channel |
public static void cancelAllNotifaction(Context context)
context
: Context
objectXGPushManager.cancelAllNotifaction(context);
public static void createNotificationChannel(Context context, String channelId, String channelName, boolean enableVibration, boolean enableLights, boolean enableSound, Uri soundUri)
context
: Context of current applicationchannelId
: Notification channel IDchannelName
: Notification channel nameenableVibration
: Whether to enable vibrationenableLights
: Whether to enable LED indicatorenableSound
: Whether to enable soundsoundUri
: Ringtone resource URI, which is valid if enableSound
is true
. To use the system-default ringtone, set this parameter to null
.// Place the sound file under the Android project resource directory `raw`. Take the file `ring.mp3` as an example.String uri = "android.resource://" + context.getPackageName() + "/" + R.raw.ring;Uri soundUri = Uri.parse(uri);XGPushManager.createNotificationChannel(context, "default_message", "Default notification", true, true, true, soundUri);
XGPushBaseReceiver
API to implement and handle all the operations on its own. In other words, delivered messages are not displayed on the notification bar by default, and Tencent Push Notification Service is responsible only for delivering messages from the Tencent Push Notification Service server to the application, but not processing the messages. The messages need to be processed by the application.XGPushBaseReceiver
and configure the following in the configuration file:<receiver android:name="com.tencent.android.xg.cloud.demo.MessageReceiver"><intent-filter><!-- Receive in-app messages --><action android:name="com.tencent.android.xg.vip.action.PUSH_MESSAGE" /><!-- Listen for results of registration, unregistration, tag setting/deletion, and notification clicks --><action android:name="com.tencent.android.xg.vip.action.FEEDBACK" /></intent-filter></receiver>
XGPushBaseReceiver
and rewrites the onTextMessage
method. After successfully receiving the message, the application can handle it based on specific business scenarios.AndroidManifest.xml
, i.e., YOUR_PACKAGE.XGPushBaseReceiver
is set.public void onTextMessage(Context context,XGPushTextMessage message)
context
: Current context of the applicationmessage
: Received message structureMethod | Returned Value | Default Value | Description |
getContent() | String | None | Message body content, and generally it is sufficient to deliver only this field |
getCustomContent() | String | None | Customer key-value of message |
getTitle() | String | None | Message title (the description of the in-app message delivered from the console is not a title) |
WebView.setDataDirectorySuffix()
method to specify a unique data directory suffix for each process; otherwise, app crash may occur. The sample configuration code is as follows:if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {// Starting with Android 9, you need to set different WebView data directories for the WebView instances of apps’ non-main processes.String processName = getProcessName()if (processName != null&& !processName.equals(context.getPackageName())) {WebView.setDataDirectorySuffix(processName)}}
XGPushConfig.enableShowInMsg(Context context, boolean flag);
context
: Context
object
flag
: Whether to allow in-app message display. true
: Allow; false
: Not allow; default: false
.XGPushConfig.enableShowInMsg(context, true);
// Create a local notificationXGLocalMessage local_msg = new XGLocalMessage();// Set the local message type; 1: Notification, 2: Messagelocal_msg.setType(1);// Set the message titlelocal_msg.setTitle("qq");// Set the message contentlocal_msg.setContent("ww");// Set the message date in the format of 20140502local_msg.setDate("20140930");// Set the hour when the message is triggered (in 24-hour clock system); 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 hourlocal_msg.setMin("31");// Set the message style. The default value is 0 or not setlocal_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 application by the package namelocal_msg.setAction_type(1);// Set the app-pulling pagelocal_msg.setActivity("com.qq.xgdemo.SettingActivity");// Set the URLlocal_msg.setUrl("http://www.baidu.com");// Set the Intentlocal_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 resourcelocal_msg.setRing_raw("mm");// Set the key and valueHashMap<String, Object> map = new HashMap<String, Object>();map.put("key", "v1");map.put("key2", "v2");local_msg.setCustomContent(map);// Add the notification to the local systemXGPushManager.addLocalNotification(context,local_msg);
public static void clearLocalNotifications(Context context)
context
: Context
objectXGPushManager.clearLocalNotifications(context);
public static void upsertAccounts(Context context, List<AccountInfo> accountInfoList, XGIOperateCallback callback)
context
: Context
objectaccountInfoList
: Account list, containing account types and account namescallback
: Callback of account binding operationXGIOperateCallback xgiOperateCallback = new XGIOperateCallback() {@Overridepublic void onSuccess(Object data, int flag) {Log.i("TPush", "onSuccess, data:" + data + ", flag:" + flag);}@Overridepublic void onFail(Object data, int errCode, String msg) {Log.w("TPush", "onFail, data:" + data + ", code:" + errCode + ", msg:" + msg);}};List<XGPushManager.AccountInfo> accountInfoList = new ArrayList<>();accountInfoList.add(new XGPushManager.AccountInfo(XGPushManager.AccountType.UNKNOWN.getValue(), "account-test"));XGPushManager.upsertAccounts(context, accountInfoList, xgiOperateCallback);
account_push_type
parameter settings in Push API.+[country or area code][subscriber number]
, for example, +8613711112222 (where there is a +
sign in the front, 86
is the country code, and 13711112222
is the subscriber number). If the entered mobile number does not contain a country or area code, Tencent Push Notification Service will automatically add +86
as the prefix when sending SMS messages. If the mobile number contains a country or area code, it will be bound as is. To delete the bound mobile number, call the delAccountsByKeys
API and set accountTypeSet
to 1002
.public static void upsertPhoneNumber(Context context, String phoneNumber, XGIOperateCallback callback)
context
: Context
objectphoneNumber
: An E.164 mobile number in the format of [+][country code or area code][mobile number]
, for example, +8613711112222callback
: Callback of mobile number binding operationXGIOperateCallback xgiOperateCallback = new XGIOperateCallback() {@Overridepublic void onSuccess(Object data, int flag) {Log.i("TPush", "onSuccess, data:" + data + ", flag:" + flag);}@Overridepublic void onFail(Object data, int errCode, String msg) {Log.w("TPush", "onFail, data:" + data + ", code:" + errCode + ", msg:" + msg);}};XGPushManager.upsertPhoneNumber(context, phoneNumber, xgiOperateCallback);
// Unbind the specified account (with registration callback)void delAccount(Context context, final String account, XGIOperateCallback callback)// Unbind the specified account (without registration callback)void delAccount(Context context, final String account )
context
: Context object of the current application, which cannot be null
account
: AccountXGPushManager.delAccount(getApplicationContext(),"test");
public static void delAccounts(Context context, final Set<Integer> accountTypeSet, XGIOperateCallback callback)
context
: Context
objectaccountTypeSet
: Type of the account to be unboundcallback
: Callback of account unbinding operationXGIOperateCallback xgiOperateCallback = new XGIOperateCallback() {@Overridepublic void onSuccess(Object data, int flag) {Log.i("TPush", "onSuccess, data:" + data + ", flag:" + flag);}@Overridepublic void onFail(Object data, int errCode, String msg) {Log.w("TPush", "onFail, data:" + data + ", code:" + errCode + ", msg:" + msg);}};Set<Integer> accountTypeSet = new HashSet<>();accountTypeSet.add(XGPushManager.AccountType.CUSTOM.getValue());accountTypeSet.add(XGPushManager.AccountType.IMEI.getValue());XGPushManager.delAccounts(context, accountTypeSet, xgiOperateCallback);
delAllAccount
API is disused in SDK v1.2.2.0. The clearAccounts
API is recommended.// Unbind all accounts (with registration callback)void clearAccounts(Context context, XGIOperateCallback callback)// Unbind all accounts (without registration callback)void clearAccounts(Context context)
context
: Context object of the current application, which cannot be null
XGPushManager.clearAccounts(getApplicationContext());
public static void clearAndAppendTags(Context context, String operateName, Set<String> tags)
context
: Context
objectoperateName
: User-defined operation name. The callback result will return it as-is, which is used to identify the operation to which the callback belongs.onSetTagResult
method of XGPushBaseReceiver
.String[] tags = "tag1 tag2".split(" ");Set<String> tagsSet = new HashSet<>(Arrays.asList(tags));XGPushManager.clearAndAppendTags(getApplicationContext(), "clearAndAppendTags :" + System.currentTimeMillis(), tagsSet);
addTags
API is disused in SDK v1.2.2.0. The appendTags
API is recommended.test:2, level:2
, all test:*
and level:*
tags bound with the device will be deleted before the test:2
and level:2
tags are added.test:2 level
, all historical tags of the device will be deleted before the test:2
and level
tags are added.public static void appendTags(Context context, String operateName, Set<String> tags)
context
: Context
objectoperateName
: User-defined operation name. The callback result will return it as-is, which is used to identify the operation to which the callback belongs.onSetTagResult
method of XGPushBaseReceiver
.String[] tags = "tag1 tag2".split(" ");Set<String> tagsSet = new HashSet<>(Arrays.asList(tags));XGPushManager.appendTags(getApplicationContext(), "appendTags:" + System.currentTimeMillis(), tagsSet);
deleteTags
API is disused in SDK v1.2.2.0. The delTags
API is recommended.public static void delTags(Context context, String operateName, Set<String> tags, XGIOperateCallback callback)
context
: Context
objectoperateName
: User-defined operation name. The callback result will return it as-is, which is used to identify the operation to which the callback belongs.callback
: Callback of tag deletion operationonSetTagResult
method of XGPushBaseReceiver
.XGIOperateCallback xgiOperateCallback = new XGIOperateCallback() {@Overridepublic void onSuccess(Object data, int flag) {Log.i("TPush", "onSuccess, data:" + data + ", flag:" + flag);}@Overridepublic void onFail(Object data, int errCode, String msg) {Log.w("TPush", "onFail, data:" + data + ", code:" + errCode + ", msg:" + msg);}};Set<String> tagSet = new HashSet<>();tagSet.add("tag1");tagSet.add("tag2");XGPushManager.delTags(context, "delTags", tagSet, xgiOperateCallback);
cleanTags
API is disused in SDK v1.2.2.0 and later versions. You are advised to use the clearTags
API.public static void clearTags(Context context, String operateName, XGIOperateCallback callback)
context
: Context
objectoperateName
: User-defined operation name. The callback result will return it as-is, which is used to identify the operation to which the callback belongs.callback
: Callback of tag clearing operationonSetTagResult
method of XGPushBaseReceiver
.XGIOperateCallback xgiOperateCallback = new XGIOperateCallback() {@Overridepublic void onSuccess(Object data, int flag) {Log.i("TPush", "onSuccess, data:" + data + ", flag:" + flag);}@Overridepublic void onFail(Object data, int errCode, String msg) {Log.w("TPush", "onFail, data:" + data + ", code:" + errCode + ", msg:" + msg);}};XGPushManager.clearTags(context, "clearTags", xgiOperateCallback);
public static void queryTags(final Context context, final String operateName, final int offset, final int limit, final XGIOperateCallback callback)
context
: Context
object.operateName
: Operation name defined by the user. The callback result will be returned as-is for users to distinguish the operation.offset
: Starting pointlimit
: Number of tags to get; maximum value: 100
callback
: Callback of tag getting operationonQueryTagsResult
method of XGPushBaseReceiver
.XGIOperateCallback xgiOperateCallback = new XGIOperateCallback() {@Overridepublic void onSuccess(Object data, int flag) {Log.i("TPush", "onSuccess, data:" + data + ", flag:" + flag);}@Overridepublic void onFail(Object data, int errCode, String msg) {Log.w("TPush", "onFail, data:" + data + ", code:" + errCode + ", msg:" + msg);}};XGPushManager.queryTags(context, 0, 100, xgiOperateCallback);
public static void upsertAttributes(Context context, String operateName, Map<String, String> attributes, XGIOperateCallback callback)
context
: Context
objectoperateName
: Operation name defined by the user. The callback result will be returned as-is for users to distinguish the operation.attributes
: Attribute set, where each attribute is identified by key-value
callback
: Callback of attribute adding operationkey
and value
of an attribute can contain up to 50 characters.XGIOperateCallback xgiOperateCallback = new XGIOperateCallback() {@Overridepublic void onSuccess(Object data, int flag) {log("action - onSuccess, data:" + data + ", flag:" + flag);}@Overridepublic void onFail(Object data, int errCode, String msg) {log("action - onFail, data:" + data + ", code:" + errCode + ", msg:" + msg);}};Map<String,String> attr = new HashMap<>();attr.put("name", "coding-test");attr.put("gender", "male");attr.put("age", "100");XGPushManager.upsertAttributes(context, "addAttributes-test", attr, xgiOperateCallback);
public static void delAttributes(Context context, String operateName, Set<String> attributes, XGIOperateCallback callback)
context
: Context
objectoperateName
: Operation name defined by the user. The callback result will be returned as-is for users to distinguish the operation.attributes
: Attribute set, where each attribute is identified by key-value
callback
: Callback of attribute deleting operationkey
and value
of an attribute can contain up to 50 characters.XGIOperateCallback xgiOperateCallback = new XGIOperateCallback() {@Overridepublic void onSuccess(Object data, int flag) {log("action - onSuccess, data:" + data + ", flag:" + flag);}@Overridepublic void onFail(Object data, int errCode, String msg) {log("action - onFail, data:" + data + ", code:" + errCode + ", msg:" + msg);}};Set<String> stringSet = new HashSet<>();stringSet.add("name");stringSet.add("gender");XGPushManager.delAttributes(context, "delAttributes-test", stringSet, xgiOperateCallback);
public static void clearAttributes(Context context, String operateName, XGIOperateCallback callback)
context
: Context
objectoperateName
: Operation name defined by the user. The callback result will be returned as-is for users to distinguish the operation.callback
: Callback of attribute clearing operationXGIOperateCallback xgiOperateCallback = new XGIOperateCallback() {@Overridepublic void onSuccess(Object data, int flag) {log("action - onSuccess, data:" + data + ", flag:" + flag);}@Overridepublic void onFail(Object data, int errCode, String msg) {log("action - onFail, data:" + data + ", code:" + errCode + ", msg:" + msg);}};XGPushManager.clearAttributes(context, "cleanAttributes-test", xgiOperateCallback);
key
and value
of an attribute can contain up to 50 characters.public static void clearAndAppendAttributes(Context context, String operateName, Map<String, String> attributes, XGIOperateCallback callback)
context
: Context
objectoperateName
: Operation name defined by the user. The callback result will be returned as-is for users to distinguish the operation.attributes
: Attribute set, where each attribute is identified by key-value
callback
: Callback of attribute setting operationXGIOperateCallback xgiOperateCallback = new XGIOperateCallback() {@Overridepublic void onSuccess(Object data, int flag) {log("action - onSuccess, data:" + data + ", flag:" + flag);}@Overridepublic void onFail(Object data, int errCode, String msg) {log("action - onFail, data:" + data + ", code:" + errCode + ", msg:" + msg);}};Map<String,String> attr = new HashMap<>();attr.put("name", "coding-test");attr.put("gender", "male");attr.put("age", "100");XGPushManager.clearAndAppendAttributes(context, "setAttributes-test", attr, xgiOperateCallback);
XGPushConfig
class. For configurations to take effect in time, you need to ensure that configuration APIs are called before launching or registering Tencent Push Notification Service.onCreate
of Application
or LauncherActivity
during application initialization and pass in false
:XGPushConfig.enablePullUpOtherApp(Context context, boolean pullUp);
context
: Application contextpullUp
: true
(enable session keep-alive); false
(disable session keep-alive)I/TPNS: [ServiceUtil] disable pull up other app
.XGPushConfig.enablePullUpOtherApp(context, false); // Default value: true (enable keep-alive)
public static void enableDebug(Context context, boolean debugMode)
context
: Context object of the applicationdebugMode
: The default value is false
. To enable debug logging, set it to true
.XGPushConfig.enableDebug(context, true); // Default value: false (do not enable)
onSuccess(Object data, int flag)
method of the registration API with XGIOperateCallback
, the data
parameter is the token. For more information, see the relevant sample of the registration API.onRegisterResult (Context context, int errorCode,XGPushRegisterResult registerMessage)
method of XGPushBaseReceiver
and get the token through the getToken
API provided by the registerMessage
parameter. For more information, see Getting registration results.XGPushConfig.getToken(context)
API.
Token is the identity ID of a device. It is randomly generated by the server based on the device attributes and delivered to the local system. The token of the same application varies by device.public static String getToken(Context context)
context
: Context object of the applicationXGPushConfig.getToken(context);
null
or 0
upon failure.public static String getOtherPushToken(Context context)
null
will be returned.context
: Context object of the applicationXGPushConfig.getOtherPushToken(context);
null
or 0
upon failure. public static String getCustomContentFromIntent(Context context, Intent intent)
context
: Context
object, which cannot be null
this.getIntent()
in onCreate, and pass in the intent
called back in onNewIntent.String customContent = XGPushManager.getCustomContentFromIntent(this, intent);
AccessID
accessKey
is already set in AndroidManifest.xml
, you do not need to call this API again; if you still call this API, the accessKey
set through this API will prevail.public static boolean setAccessId(Context context, long accessId)
Context
: ObjectaccessId
: accessId
obtained through registration in the consolelong accessId = 0L; // `accessId` of the current applicationXGPushConfig.setAccessId(context, accessId);
accessId
set through this API will also be stored in the AndroidManifest.xml
file.accessKey
accessKey
is already set in AndroidManifest.xml
, you do not need to call this API again; if you still call this API, the accessKey
set through this API will prevail.public static boolean setAccessKey(Context context, String accessKey)
Context
: ObjectaccessKey
: accessKey
obtained through registration in the consoleString accessKey = ""; // `accessKey` of your applicationXGPushConfig.setAccessKey(context, accessKey);
AndroidManifest.xml
file.public static void uploadLogFile(Context context, HttpRequestCallback httpRequestCallback)
context
: Context
object, which cannot be null
httpRequestCallback
: Log reporting result callback, which include callbacks for success and failure and cannot be null
XGPushManager.uploadLogFile(context, new HttpRequestCallback() {@Overridepublic void onSuccess(String result) {Log.d("TPush", "Upload succeeded. File address:" + result);}@Overridepublic void onFailure(int errCode, String errMsg) {Log.d("TPush", "Upload failed. Error code:" + errCode + ", error message:" + errMsg);}});
XGPushConfig.enableDebug(this, true);
first.
Was this page helpful?