Integrate the Android SDK (4.x)
This document describes how to integrate version 4.x of the Mobile Push Android SDK, including adding the SDK, initialization and device registration, configuring message receiving, integrating vendor channels, and verifying the integration.
Introduction
-
We recommend using a Gradle-based Android Studio project.
-
The minimum supported version is Android 6.0 (API 23).
-
This document applies to version 4.x of the Mobile Push Android SDK.
The Mobile Push SDK includes both a proprietary channel and vendor channels. Integrating vendor channels improves notification delivery when your app is offline. This guide uses version 4.0.0 as an example.
To upgrade a project from version 3.x, see the Android SDK 4.x Upgrade Guide. For projects still on version 3.x, see Android SDK Integration (3.x).
Before you begin
In the EMAS console, create or select an Android application, enable Mobile Push, and record the AppKey and AppSecret. Ensure the applicationId (package name) of your APK matches the one registered in the console. For detailed instructions, see Create Application.
|
Build environment |
Minimum supported version |
|
Android version |
Android 6.0 (API 23) or later |
|
compileSdk |
34 or later |
|
Android Gradle Plugin (AGP) |
8.1.1 or later |
|
Gradle |
8.0 or later |
|
Build JDK |
17 or later |
|
Kotlin (Kotlin projects only) |
1.8.0 or later |
The tools listed are the minimum required versions for compileSdk 34. If you use a newer version of the Android Gradle Plugin (AGP), you must also use the corresponding required versions of Gradle and the build JDK.
Step 1: Add the SDK
We recommend integrating the SDK using a Maven dependency. The following Groovy examples show how to update your project's repository and dependency configurations.
1. Use a Maven dependency
1.1 Configure the Maven repository
If your project uses dependencyResolutionManagement to manage dependencies, add the repository to the repositories block in your project-level settings.gradle file.
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven { url 'https://maven.aliyun.com/nexus/content/repositories/releases/' }
}
}
If your project uses allprojects to manage dependencies, add the repository to the repositories block in your project-level build.gradle file.
allprojects {
repositories {
google()
mavenCentral()
maven { url 'https://maven.aliyun.com/nexus/content/repositories/releases/' }
}
}
Choose the repository configuration that matches your project's structure. When integrating vendor channels such as Huawei or Honor, add their Maven repositories as specified in their documentation.
1.2 Add the SDK dependency
In your app module's build.gradle file, add the SDK dependency to the dependencies block.
dependencies {
implementation 'com.aliyun.ams:alicloud-android-push:4.0.0'
}
Use a fixed version number for integration, retain Maven's transitive dependencies, and manage all SDKs through Maven. Using dynamic version numbers like 4.+, @aar, or transitive = false can cause unpredictable version and dependency resolution. Do not place SDKs already included via Maven into the libs directory.
Maven automatically downloads all required dependencies for version 4.x. Copying the main SDK's AAR file alone is insufficient for a complete integration. If you are upgrading an existing project, follow the upgrade guide to handle legacy dependencies.
Step 2: Configure the SDK
1. Configure the AppKey and AppSecret
You can configure the AppKey and AppSecret either in your code or in the AndroidManifest.xml file. Ensure the AppKey and AppSecret correspond to the same application in the EMAS console.
1.1 Code configuration
In your Application class, build a PushInitConfig object to use for initialization.
PushInitConfig pushInitConfig = new PushInitConfig.Builder()
.application(this) // The current Application instance
.appKey("YOUR_APP_KEY")
.appSecret("YOUR_APP_SECRET")
.build();val pushInitConfig = PushInitConfig.Builder()
.application(this) // The current Application instance
.appKey("YOUR_APP_KEY")
.appSecret("YOUR_APP_SECRET")
.build()1.2 AndroidManifest configuration
Configure the application parameters within the <application> node of your AndroidManifest.xml file.
<application ...>
<meta-data android:name="com.alibaba.app.appkey" android:value="YOUR_APP_KEY" />
<meta-data android:name="com.alibaba.app.appsecret" android:value="YOUR_APP_SECRET" />
</application>
2. SDK initialization and device registration
2.1 Initialize the SDK
In the onCreate() method of your custom Application class, call PushServiceFactory.init on the main thread. Ensure this initialization logic runs in all processes that require push notification capabilities.
If you use code-based configuration, pass the PushInitConfig object created in the previous step to the init method.
PushServiceFactory.init(pushInitConfig);PushServiceFactory.init(pushInitConfig)If you use AndroidManifest configuration, initialize the SDK with a Context object.
PushServiceFactory.init(getApplicationContext());PushServiceFactory.init(applicationContext)Declare your custom Application in AndroidManifest.xml. Replace PushApplication with your actual class name.
<application
android:name=".PushApplication"
...>
<!-- Keep your existing application configurations. -->
</application>
2.2 Register the device
Device registration starts the push connection. Call this method only after your app has met its privacy and consent requirements, and after the SDK has been initialized. If you have not customized the push service process, run the registration logic in the main process. Otherwise, run it in the custom process that you have defined.
final CloudPushService pushService = PushServiceFactory.getCloudPushService();
// Enable logging and configuration checks during integration testing.
pushService.setLogLevel(CloudPushService.LOG_DEBUG);
pushService.setDebug(true);
pushService.register(this, new CommonCallback() {
@Override
public void onSuccess(String response) {
String deviceId = pushService.getDeviceId();
Log.d("PushDemo", "register success, deviceId=" + deviceId);
// Save the deviceId for targeted pushes from the console or your server.
}
@Override
public void onFailed(String errorCode, String errorMessage) {
Log.e("PushDemo", "register failed: " + errorCode + ", " + errorMessage);
}
});val pushService = PushServiceFactory.getCloudPushService()
// Enable logging and configuration checks during integration testing.
pushService.setLogLevel(CloudPushService.LOG_DEBUG)
pushService.setDebug(true)
pushService.register(this, object : CommonCallback {
override fun onSuccess(response: String?) {
val deviceId = pushService.deviceId
Log.d("PushDemo", "register success, deviceId=$deviceId")
// Save the deviceId for targeted pushes from the console or your server.
}
override fun onFailed(errorCode: String?, errorMessage: String?) {
Log.e("PushDemo", "register failed: $errorCode, $errorMessage")
}
})Register the device by using register(Context, CommonCallback) and provide a non-null callback. In the onSuccess callback, retrieve the device ID by calling getDeviceId(). This ID is used for targeted pushes.
Set the log level after init but before register and vendor channel initialization. setDebug(true) is for integration configuration checks and is not the same as enabling DEBUG logs. Before releasing your app, change the log level to LOG_ERROR and remove the call to setDebug(true).
For more information on initialization, device identifiers, logging, and receiving methods, see Basic Configuration APIs (4.x).
3. Configure notification channels and permissions
3.1 Create a notification channel
On Android 8.0 (API level 26) and higher, you must create a NotificationChannel. The example below shows how to create a notification channel in the Application class. When you send pushes from the server, the AndroidNotificationChannel parameter must match the client's channelId.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager manager = getSystemService(NotificationManager.class);
String channelId = "push_default";
NotificationChannel channel = new NotificationChannel(
channelId, "Message notifications", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val manager = getSystemService(NotificationManager::class.java)
val channelId = "push_default"
val channel = NotificationChannel(
channelId, "Message notifications", NotificationManager.IMPORTANCE_DEFAULT
)
manager.createNotificationChannel(channel)
}3.2 Request the notification permission
On Android 13 (API level 33) and higher, you must request the POST_NOTIFICATIONS runtime permission. First, declare the permission in your AndroidManifest.xml file. Then, request the permission at an appropriate time in your Activity and handle the authorization result. The following example applies to apps that target targetSdk 33 or higher.
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
package com.example.pushdemo;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
public class MainActivity extends Activity {
private static final int REQUEST_NOTIFICATIONS = 1001;
// In the Activity, request notification permission at an appropriate time,
// such as when the user actively enables push notifications.
public void requestPushNotificationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
&& checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(
new String[]{Manifest.permission.POST_NOTIFICATIONS},
REQUEST_NOTIFICATIONS);
}
}
@Override
public void onRequestPermissionsResult(
int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_NOTIFICATIONS) {
boolean granted = grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED;
Log.d("PushDemo", "notification permission granted=" + granted);
// If permission is denied, inform the user that notification functionality
// is limited, according to your app's UI/UX design.
}
}
}package com.example.pushdemo
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
class MainActivity : Activity() {
private val requestNotifications = 1001
fun requestPushNotificationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED
) {
requestPermissions(
arrayOf(Manifest.permission.POST_NOTIFICATIONS), requestNotifications
)
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>, grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == requestNotifications) {
val granted = grantResults.isNotEmpty() &&
grantResults[0] == PackageManager.PERMISSION_GRANTED
Log.d("PushDemo", "notification permission granted=$granted")
}
}
}Notifications are displayed only if your app has the notification permission, the app-level notification toggle is on, and the specific notification channel is enabled. Verify each part of the process separately: permission status, notification display, and pass-through message delivery.
4. Configure message receiving
In Android SDK 4.x, the scope of business callbacks for MessageReceiver and AliyunMessageIntentService is as follows:
The ACCS proprietary channel and FCM support all callbacks:
onMessage(message received),onNotification(notification arrived),onNotificationOpened(notification clicked), andonNotificationRemoved(notification dismissed).Other Android vendor channels (excluding FCM) only support the
onNotificationOpened(notification clicked) callback. Callbacks for message arrival, notification arrival, or dismissal are not triggered.
Create a MyMessageReceiver class that extends MessageReceiver and override the callback methods you need. In the example, PushDemo is a custom log tag used to observe callbacks. The SDK's logs use the EMAS_PUSH tag.
package com.example.pushdemo;
import android.content.Context;
import android.util.Log;
import com.alibaba.sdk.android.push.MessageReceiver;
import com.alibaba.sdk.android.push.notification.CPushMessage;
import java.util.Map;
public class MyMessageReceiver extends MessageReceiver {
private static final String TAG = "PushDemo";
@Override
public void onMessage(Context context, CPushMessage message) {
Log.d(TAG, "message received");
// Pass-through messages must be handled by the app;
// the SDK does not automatically display them as notifications.
}
@Override
public void onNotification(Context context, String title, String summary,
Map<String, String> extraMap) {
Log.d(TAG, "notification received");
}
@Override
public void onNotificationOpened(Context context, String title, String summary,
Map<String, String> extraMap) {
Log.d(TAG, "notification opened");
// Handle notification clicks based on your business logic.
// You can retrieve extended parameters from extraMap.
}
@Override
public void onNotificationRemoved(Context context, String messageId) {
Log.d(TAG, "notification removed");
}
}package com.example.pushdemo
import android.content.Context
import android.util.Log
import com.alibaba.sdk.android.push.MessageReceiver
import com.alibaba.sdk.android.push.notification.CPushMessage
class MyMessageReceiver : MessageReceiver() {
override fun onMessage(context: Context, message: CPushMessage) {
Log.d("PushDemo", "message received")
// Pass-through messages must be handled by the app.
}
override fun onNotification(
context: Context, title: String?, summary: String?, extraMap: Map<String, String>?
) {
Log.d("PushDemo", "notification received")
}
override fun onNotificationOpened(
context: Context, title: String?, summary: String?, extraMap: Map<String, String>?
) {
Log.d("PushDemo", "notification opened")
// Handle notification clicks based on your business logic.
// You can retrieve extended parameters from extraMap.
}
override fun onNotificationRemoved(context: Context, messageId: String?) {
Log.d("PushDemo", "notification removed")
}
}Declare the Receiver in the <application> node of your AndroidManifest.xml file. The SDK's own components and basic permissions are automatically merged from the AAR's manifest.
<application ...>
<receiver
android:name=".MyMessageReceiver"
android:exported="false">
<intent-filter>
<action android:name="com.alibaba.sdk.android.push.RECEIVE" />
<action android:name="com.alibaba.push2.action.NOTIFICATION_OPENED" />
<action android:name="com.alibaba.push2.action.NOTIFICATION_REMOVED" />
</intent-filter>
</receiver>
</application>
For details on callback threads and timing, notification display control, and how to use AliyunMessageIntentService for receiving messages, see Message and Notification Handling APIs (4.x). Avoid time-consuming operations in callbacks.
5. Configure NDK and obfuscation
5.1 NDK configuration
The SDK's transitive dependencies include libels.so and libjnidispatch.so, which support arm64-v8a, armeabi-v7a, x86, and x86_64. If you use abiFilters or split your APK/AAB, ensure these library files are included for your target ABIs.
5.2 Obfuscation and build verification
The 4.0.0 main SDK and its transitive dependencies include consumer ProGuard rules that are automatically merged during Maven integration. If your app or any vendor SDKs have additional obfuscation requirements, configure them according to their respective documentation.
Use a release build with obfuscation enabled to verify initialization and message receiving. If you encounter class or native library conflicts, first use the dependency tree to identify duplicate dependencies. Also, verify that the final APK includes the necessary native libraries (.so files) for your target ABIs.
./gradlew :app:dependencies --configuration releaseRuntimeClasspath
./gradlew :app:assembleRelease
Step 3: Integrate vendor channels
We recommend integrating vendor channels to improve notification delivery rates when your app is offline. For each channel you choose, complete the application registration on the vendor's platform, configure the parameters in the EMAS console, initialize the vendor's SDK, and configure notification click handling.
dependencies {
// If you need vendor channels, add the common component and
// select the adapters for the channels you want to integrate.
implementation 'com.aliyun.ams:alicloud-android-third-push:4.0.0'
// implementation 'com.aliyun.ams:alicloud-android-third-push-xiaomi:4.0.0'
// implementation 'com.aliyun.ams:alicloud-android-third-push-huawei:4.0.0'
// implementation 'com.aliyun.ams:alicloud-android-third-push-honor:4.0.0'
// implementation 'com.aliyun.ams:alicloud-android-third-push-oppo:4.0.0'
// implementation 'com.aliyun.ams:alicloud-android-third-push-vivo:4.0.0'
// implementation 'com.aliyun.ams:alicloud-android-third-push-meizu:4.0.0'
// implementation 'com.aliyun.ams:alicloud-android-third-push-fcm:4.0.0'
}
Ensure you use the same version (e.g., 4.0.0) for the main SDK, the third-party common component (alicloud-android-third-push), and all vendor adapters. The versions of the native vendor SDKs are managed by the Maven dependencies of their corresponding extension packages.
Based on the device manufacturer, follow the corresponding instructions in Vendor Channel Integration. To handle clicks on system notifications from vendors like Xiaomi, Huawei, Honor, OPPO, vivo, and Meizu, you must complete the Helper Activity Integration (4.x) and process the click event in onNotificationOpened. For FCM, the adapter forwards data messages to the Mobile Push SDK, so the helper activity is not required.
Step 4: Verify the integration
1. Enable SDK logs
The 4.x SDK uses the EMAS_PUSH tag for all logs, with module information included in the log message. You can filter by tag:EMAS_PUSH in Android Studio's Logcat or run the following command. Logs that are output directly by third-party SDKs and the Android system will use their respective tags.
adb logcat -s EMAS_PUSH
During debugging, explicitly set the log level to LOG_DEBUG after init but before register and vendor SDK initialization. setDebug(true) is for integration checks and is not the same as enabling DEBUG logs. The example app's callback logs use the PushDemo tag, so you can filter for both tags at the same time:
adb logcat -s EMAS_PUSH PushDemo
2. Verify the integration result
|
Verification item |
Action and criteria |
|
Dependencies and Components |
The build succeeds, and the final package contains the required components. The app installs and initializes without crashing. |
|
Device Registration |
Verify that the |
|
Pass-through Message |
From the console, send a pass-through message to the |
|
Notification Display |
First, send a notification to the same |
|
Click and Deletion |
Click notifications sent through the ACCS proprietary channel and vendor channels. Check the |
|
Vendor Offline Scenario |
For each integrated vendor, verify channel registration, offline notification display, and click-through actions. Confirm that the corresponding parameters are correctly set on the server side. |
|
Release Build |
Repeat the verification by using a release build with obfuscation enabled. Test with the app in the foreground, in the background, and after it has been terminated. |
A successful register callback confirms device registration, and a successful API call to send a message confirms the server accepted the request. However, you must still verify the entire end-to-end push flow by checking device callbacks, notification tray behavior, and click actions.
If you encounter errors, see Error Handling (4.x). For information on additional APIs, see the Android SDK 4.x API.