Basic configuration API (4.x)

Updated at:

This topic describes the Android SDK 4.x interfaces for initialization, registration, device identification, push controls, logging, and notification permissions.

Note

This document covers Mobile Push Android SDK 4.x. All interfaces and examples are based on version 4.0.0. For applications using 3.x, refer to the 3.x API documentation.

Initialization and call sequence

Initialize the SDK in your application's Application.onCreate() method. The init method configures the SDK, and the register method registers the push service. Call register after your application meets business requirements, such as privacy consent.

The following classes are located in com.alibaba.sdk.android.push.noonesdk (PushInitConfig, PushServiceFactory) and com.alibaba.sdk.android.push (CloudPushService, CommonCallback).

In the following code samples, application refers to the Application instance of your app. Call CloudPushService APIs only after initialization is complete. Perform business operations, such as managing accounts and tags, only after registration is successful.

Initialize with a configuration object (init)

Use a PushInitConfig object to provide the Application instance, AppKey, and AppSecret.

Class: PushServiceFactory.

Interface definition

public static void init(PushInitConfig pushInitConfig);

Parameters

Parameter

Type

Required

Description

pushInitConfig

PushInitConfig

Yes

The configuration object for initialization. Its application property must be a non-null Application instance.

Return value

None (void).

Code sample

PushInitConfig config = new PushInitConfig.Builder()
        .application(application)
        .appKey("YOUR_APP_KEY")
        .appSecret("YOUR_APP_SECRET")
        .build();
PushServiceFactory.init(config);
val config = PushInitConfig.Builder()
    .application(application)
    .appKey("YOUR_APP_KEY")
    .appSecret("YOUR_APP_SECRET")
    .build()
PushServiceFactory.init(config)

Initialize using Manifest configuration (init)

Initializes the SDK by reading the AppKey and AppSecret configured in the AndroidManifest.xml file.

Before using this overload, you must configure com.alibaba.app.appkey and com.alibaba.app.appsecret under the application node in your AndroidManifest.xml file. Use only one of the two init methods. Each call to init restores the default MessageReceiver dispatching method. If you need to use a custom IntentService, you must set it after initialization.

Class: PushServiceFactory.

Interface definition

public static void init(Context appContext);

Parameters

Parameter

Type

Required

Description

appContext

Context

Yes

The application context, which cannot be null.

Return value

None (void).

Code sample

PushServiceFactory.init(application.getApplicationContext());
PushServiceFactory.init(application.applicationContext)

Get the push service instance (getCloudPushService)

Returns the singleton CloudPushService instance. Use this instance to perform operations such as registration and managing the push switch.

Class: PushServiceFactory.

Interface definition

public static CloudPushService getCloudPushService();

Parameters

None.

Return value

CloudPushService: The push service instance. Retrieving this instance does not automatically initialize or register the SDK.

Code sample

CloudPushService pushService = PushServiceFactory.getCloudPushService();
val pushService = PushServiceFactory.getCloudPushService()

Initialization configuration (PushInitConfig.Builder)

Use the following methods to build the configuration object passed to the init method.

Configuration method

Parameter

Description

PushInitConfig.Builder application(Application application)

Application

Required. The Application instance of your app.

PushInitConfig.Builder appKey(String appKey)

String

The AppKey of your EMAS application. Optional if already configured in the AndroidManifest.xml file.

PushInitConfig.Builder appSecret(String appSecret)

String

The AppSecret corresponding to the AppKey. Optional if already configured in the AndroidManifest.xml file.

PushInitConfig build()

None

Builds and returns the PushInitConfig object.

Configure the application (application)

Sets the Application instance for your app. This parameter cannot be null.

Class: PushInitConfig.Builder.

Interface definition

public PushInitConfig.Builder application(Application application);

Parameters

Parameter

Type

Required

Description

application

Application

Yes

Specifies the Application instance for your app. This parameter cannot be null.

Return value

PushInitConfig.Builder: The same Builder instance, to allow for method chaining.

Code sample

PushInitConfig.Builder builder = new PushInitConfig.Builder();
builder.application(application);
val builder = PushInitConfig.Builder()
builder.application(application)

Configure the AppKey (appKey)

Sets the AppKey for your EMAS application. This step is optional if the AppKey is already configured in your AndroidManifest.xml. The AppKey must correspond to the AppSecret.

Class: PushInitConfig.Builder.

Interface definition

public PushInitConfig.Builder appKey(String appKey);

Parameters

Parameter

Type

Required

Description

appKey

String

No

The AppKey of your EMAS application. This is optional if already configured in the Manifest file. It must correspond to the AppSecret.

Return value

PushInitConfig.Builder: The same Builder instance, to allow for method chaining.

Code sample

PushInitConfig.Builder builder = new PushInitConfig.Builder().application(application);
builder.appKey("YOUR_APP_KEY");
val builder = PushInitConfig.Builder().application(application)
builder.appKey("YOUR_APP_KEY")

Configure the AppSecret (appSecret)

Sets the AppSecret for your EMAS application. This step is optional if the AppSecret is already configured in your AndroidManifest.xml. The AppSecret must correspond to the AppKey.

Class: PushInitConfig.Builder.

Interface definition

public PushInitConfig.Builder appSecret(String appSecret);

Parameters

Parameter

Type

Required

Description

appSecret

String

No

The AppSecret of your EMAS application. This is optional if already configured in the Manifest file. It must correspond to the AppKey.

Return value

PushInitConfig.Builder: The same Builder instance, to allow for method chaining.

Code sample

PushInitConfig.Builder builder = new PushInitConfig.Builder().application(application);
builder.appSecret("YOUR_APP_SECRET");
val builder = PushInitConfig.Builder().application(application)
builder.appSecret("YOUR_APP_SECRET")

Build the configuration object (build)

Builds and returns a PushInitConfig object from the provided configuration.

Class: PushInitConfig.Builder.

Interface definition

public PushInitConfig build();

Parameters

None.

Return value

PushInitConfig: The configured PushInitConfig object, ready to be passed to PushServiceFactory.init().

Code sample

// In this sample, AppKey and AppSecret are configured in the Manifest.
PushInitConfig config = new PushInitConfig.Builder()
        .application(application)
        .build();
// In this sample, AppKey and AppSecret are configured in the Manifest.
val config = PushInitConfig.Builder()
    .application(application)
    .build()

Register the push notification service

Registers the current application and device with Mobile Push. After successful registration, you can retrieve the device ID and call business APIs.

Class: CloudPushService.

API definition

void register(Context context, CommonCallback callback);

Parameters

Parameter

Type

Required

Description

context

Context

Yes

Use ApplicationContext. This value must not be null.

callback

CommonCallback

Yes

A callback to handle the registration result.

Return value and callback

This method returns void. The onSuccess(response) callback is invoked on success, and the onFailed(errorCode, errorMessage) callback is invoked on failure.

Code sample

CloudPushService pushService = PushServiceFactory.getCloudPushService();
pushService.register(application.getApplicationContext(), new CommonCallback() {
    @Override public void onSuccess(String response) {
        String deviceId = pushService.getDeviceId();
        // Save the registration status and deviceId based on your business requirements.
    }
    @Override public void onFailed(String errorCode, String errorMessage) {
        // Troubleshoot based on the error code and SDK logs.
    }
});
val pushService = PushServiceFactory.getCloudPushService()
pushService.register(application.applicationContext, object : CommonCallback {
    override fun onSuccess(response: String?) {
        val deviceId = pushService.deviceId
    }
    override fun onFailed(errorCode: String?, errorMessage: String?) {
        // Troubleshoot based on the error code and SDK logs.
    }
})
Note

CommonCallback defines onSuccess(String response) and onFailed(String errorCode, String errorMessage). Any UI updates performed in the callback must be executed on the main thread.

Callback method

Parameter

Type

Description

onSuccess

response

String

The response returned upon successful registration.

onFailed

errorCode

String

An error code that identifies the cause of failure.

onFailed

errorMessage

String

A human-readable description of the error.

Get the device ID

Class: CloudPushService.

Interface definition

String getDeviceId();

Parameters

None.

Return value

Type

Description

String

Returns the Mobile Push device ID, used to target server-side push notifications to the device. This ID should be retrieved after a successful registration. The return value may be empty if initialization or registration is incomplete.

Code example

String deviceId = PushServiceFactory.getCloudPushService().getDeviceId();
val deviceId = PushServiceFactory.getCloudPushService().deviceId

Enable the push channel (turnOnPushChannel)

Class: CloudPushService.

Interface definition

void turnOnPushChannel(CommonCallback callback);

Enables the push channel for the current device. You must check the android system notification permission and the ACCS connection status separately.

Parameters

Parameter

Type

Required

Description

callback

CommonCallback

No

The operation callback. Recommended for confirming whether the channel was enabled.

Return value and callback

This method returns void. A successful operation invokes the onSuccess(response) callback. A failed operation invokes the onFailed(errorCode, errorMessage) callback, which provides an error code and an error message.

Code sample

PushServiceFactory.getCloudPushService().turnOnPushChannel(new CommonCallback() {
    @Override public void onSuccess(String response) {
        // The push channel is enabled.
    }
    @Override public void onFailed(String errorCode, String errorMessage) {
        // Handle the failure based on the error code and message.
    }
});
PushServiceFactory.getCloudPushService().turnOnPushChannel(object : CommonCallback {
    override fun onSuccess(response: String?) {
        // The push channel is enabled.
    }
    override fun onFailed(errorCode: String?, errorMessage: String?) {
        // Handle the failure based on the error code and message.
    }
})

Disable the push channel (turnOffPushChannel)

Disables the push channel for the current device. To resume receiving notifications, call turnOnPushChannel.

Class: CloudPushService.

Interface definition

void turnOffPushChannel(CommonCallback callback);

Parameters

Parameter

Type

Required

Description

callback

CommonCallback

No

A callback invoked with the operation's result. Recommended for handling success or failure.

Return value and callback

This method returns void. The onSuccess(response) callback is invoked when the operation succeeds. On failure, the onFailed(errorCode, errorMessage) callback is invoked with an error code and error message.

Code sample

PushServiceFactory.getCloudPushService().turnOffPushChannel(new CommonCallback() {
    @Override public void onSuccess(String response) {
        // The push channel is disabled.
    }
    @Override public void onFailed(String errorCode, String errorMessage) {
        // Handle the failure based on the error code and error message.
    }
});
PushServiceFactory.getCloudPushService().turnOffPushChannel(object : CommonCallback {
    override fun onSuccess(response: String?) {
        // The push channel is disabled.
    }
    override fun onFailed(errorCode: String?, errorMessage: String?) {
        // Handle the failure based on the error code and error message.
    }
})

Check push channel status (checkPushChannelStatus)

Checks the status of the push channel for the current device. To check the device connection status, use the connection logs. To check notification permissions, use the Android system APIs.

Class: CloudPushService.

API definition

void checkPushChannelStatus(CommonCallback callback);

Parameters

Parameter

Type

Required

Description

callback

CommonCallback

No

The callback to receive the channel status.

Return value and callback

This method returns void. The response from the onSuccess(response) callback is either 'on' or 'off'. If the query fails, the onFailed(errorCode, errorMessage) callback is called.

Code sample

PushServiceFactory.getCloudPushService().checkPushChannelStatus(new CommonCallback() {
    @Override public void onSuccess(String response) {
        // The response is "on" (enabled) or "off" (disabled).
    }
    @Override public void onFailed(String errorCode, String errorMessage) {
        // Handle the failure based on the error code and message.
    }
});
PushServiceFactory.getCloudPushService().checkPushChannelStatus(object : CommonCallback {
    override fun onSuccess(response: String?) {
        // The response is "on" (enabled) or "off" (disabled).
    }
    override fun onFailed(errorCode: String?, errorMessage: String?) {
        // Handle the failure based on the error code and message.
    }
})

Configure the message receiving service

Important

In Android SDK 4.x, MessageReceiver and AliyunMessageIntentService support the following callbacks:

  • ACCS proprietary channel and FCM: Support all callbacks: onMessage, onNotification, onNotificationOpened, and onNotificationRemoved.

  • Android vendor channels other than FCM: Only support onNotificationOpened. Other callbacks, such as onMessage, onNotification, and onNotificationRemoved, are not invoked.

Class: CloudPushService.

Interface definition

void setPushIntentService(Class intentService);

By default, MessageReceiver handles messages. To use AliyunMessageIntentService, set your custom service class in Application.onCreate() as soon as init is complete on each application startup, and declare the service in the manifest. Once set, MessageReceiver stops receiving message and notification callbacks. Passing null restores the broadcast-based approach.

Parameters

Parameter

Type

Required

Description

intentService

Class

No

A custom service class that extends AliyunMessageIntentService. Passing null reverts to using MessageReceiver.

Return value

None.

Code sample

PushServiceFactory.getCloudPushService()
        .setPushIntentService(MyMessageIntentService.class);
PushServiceFactory.getCloudPushService()
    .setPushIntentService(MyMessageIntentService::class.java)

MyMessageIntentService in the sample is a placeholder for the custom service class that you create and declare in the manifest. For implementation details, see Message and notification handling interface (4.x).

Set the log level (setLogLevel)

Sets the output level for SDK logs. Class: CloudPushService.

API signature

void setLogLevel(int logLevel);

Parameters

Parameter

Type

Required

Description

logLevel

int

Yes

The log level. Use a CloudPushService constant from the following table.

logLevel values

Constant

Description

LOG_ERROR (0)

Outputs WARN and ERROR logs. As of version 4.0.0, this constant sets the log threshold to WARN.

LOG_INFO (1)

Outputs logs at the INFO level and higher.

LOG_DEBUG (2)

For development and debugging. It outputs logs at the DEBUG level and higher.

LOG_OFF (-1)

Disables all log output from the SDK's unified log pipeline.

Returns

None (void).

To set the SDK log level, call setLogLevel after init but before register and vendor registration. Use LOG_ERROR or LOG_OFF in a production environment. If you need to adjust the filter level for underlying connection logs, apply this setting before the next startup and registration.

Code sample

// Call this after init but before register and vendor channel registration.
PushServiceFactory.getCloudPushService().setLogLevel(CloudPushService.LOG_DEBUG);
// Call this after init but before register and vendor channel registration.
PushServiceFactory.getCloudPushService().setLogLevel(CloudPushService.LOG_DEBUG)

In version 4.0.0, main SDK logs use the EMAS_PUSH Logcat tag and include the module name in the message body. In Android Studio Logcat, you can filter by tag:EMAS_PUSH and further refine your search by module name or error code.

adb logcat -s EMAS_PUSH
Note

LOG_OFF only disables output from the SDK's unified log pipeline. This setting does not control logs generated by direct calls to Android's Log class, native vendor SDKs, or system logs, which are managed by their respective configurations. Before collecting and sharing logs, mask sensitive business information, such as device identifiers.

Enable debug checks (setDebug)

Enables component and parameter checks to aid in debugging your integration. This setting does not change the log level. To view DEBUG logs, call setLogLevel separately.

Class: CloudPushService.

Method signature

void setDebug(boolean isDebug);

Parameters

Parameter

Type

Required

Description

isDebug

boolean

Yes

true: Enables checks on components and certain parameters. false: Disables these checks.

Return value

None (void).

Code sample

// Call this method after init and before register.
PushServiceFactory.getCloudPushService().setDebug(true);

Receive SDK logs

API definition

static void addListener(LoggerListener listener);

The listener receives logs from the SDK's unified logging pipeline that pass the log level filter. The primary log tag is EMAS_PUSH, and the log message includes a module prefix.

Parameters

Parameter

Type

Required

Description

listener

LoggerListener

Yes

The log listener cannot be null. Implement the d, i, w, and e callbacks to receive DEBUG, INFO, WARN, and ERROR logs, respectively.

Return value and callback

The addListener method returns void. The four callbacks in LoggerListener also return void. Their parameters are the same, as described in the table below.

Callback parameter

Type

Description

tag

String

The log tag. For primary SDK logs, the tag is EMAS_PUSH.

msg

String

The log message, which includes a module prefix.

tr

Throwable

The exception object. For the version 4.0.0 log bridge callback, this parameter is null.

flag

int

A compatibility field. For the version 4.0.0 log bridge callback, this parameter is 0.

Code sample

AmsLogger.addListener(new LoggerListener() {
    @Override public void d(String tag, String msg, Throwable tr, int flag) {}
    @Override public void i(String tag, String msg, Throwable tr, int flag) {}
    @Override public void w(String tag, String msg, Throwable tr, int flag) {
        // Handle data desensitization, sampling, and persistence in your application. Avoid making recursive calls to AmsLogger here.
    }
    @Override public void e(String tag, String msg, Throwable tr, int flag) {}
});
AmsLogger.addListener(object : LoggerListener {
    override fun d(tag: String?, msg: String?, tr: Throwable?, flag: Int) {}
    override fun i(tag: String?, msg: String?, tr: Throwable?, flag: Int) {}
    override fun w(tag: String?, msg: String?, tr: Throwable?, flag: Int) {}
    override fun e(tag: String?, msg: String?, tr: Throwable?, flag: Int) {}
})

When you persist or upload logs, use sampling as needed and limit the number of logs per run, total file size, and retention period. In a production environment, collect only the log levels required for troubleshooting.

Notification permission API

Requests the notification permission required on Android 13 and later. This method is in the CloudPushService class. The IPushPermissionCallback interface is in the com.alibaba.sdk.android.push package.

API definition

void requestNotificationPermission(Activity activity, int requestCode, IPushPermissionCallback callback);

Parameters

Parameter

Type

Required

Description

activity

Activity

Yes

The current interactive Activity.

requestCode

int

Yes

The Android runtime permission request code.

callback

IPushPermissionCallback

No

A callback for permission status updates. You can set this parameter to null, but you must still handle the final authorization result in the Activity.

Return value and callback

This method returns void. The onPushPermissionForbidden() and onPushPermissionGranted() callback methods take no parameters and return void.

Use this API to request the POST_NOTIFICATIONS permission on Android 13 and later. The permission callback in version 4.0.0 is not guaranteed to be triggered in all scenarios, so your application must check the system's authorization status in the Activity's permission result handler. If the application runs on an earlier Android version or if the permission has already been granted, query the current permission status directly.

Code sample

PushServiceFactory.getCloudPushService().requestNotificationPermission(
        activity, 1001, new IPushPermissionCallback() {
            @Override public void onPushPermissionForbidden() {
                // Explain the notification permission's purpose to the user and guide them through your UI flow.
            }
            @Override public void onPushPermissionGranted() {}
        });
// In the Activity's onRequestPermissionsResult, handle this requestCode
// and check the final status of POST_NOTIFICATIONS using the Android permission APIs.
PushServiceFactory.getCloudPushService().requestNotificationPermission(
    activity, 1001, object : IPushPermissionCallback {
        override fun onPushPermissionForbidden() {}
        override fun onPushPermissionGranted() {}
    }
)
// Recheck the final authorization status in the Activity's permission result handler.

Changes from 3.x

API or parameter

Status in 4.0.0

disableChannelProcess, disableChannelProcessHeartbeat, loopStartChannel, and loopInterval

Removed.

PushControlService and getPushControlService

Removed. The SDK no longer provides interfaces to manually reconnect, reset, or monitor the connection status.

Related documentation

For the integration process, see Android SDK integration (4.x).

For applications using version 3.x, see basic configuration API (3.x).