SoFunction
Updated on 2025-04-14

Implement message push function on Android platform

1. Project Overview

With the rapid development of mobile Internet applications, message push has become an indispensable function in mobile applications. Whether it is e-commerce, social, news or service applications, message push can convey information in real time, improve user stickiness, and bring more marketing and interaction opportunities to enterprises. On the Android platform, message push involves message sending on the server, message receiving on the client, management of notification channels, and processing of application in different states of the foreground and backend.

Project Purpose:

  • A complete solution to implement message push on Android application side.

  • With the help of third-party push platforms (such as Firebase Cloud Messaging, FCM for short) or self-built services, real-time message issuance and notification reminders are realized.

  • Combined with the application's business scenarios, it realizes functions such as front-end display, notification bar message display, and message storage and management.

Project Features

  • High real-time: By using FCM services, millisecond message arrival can be achieved.

  • Strong compatibility: Suitable for different Android versions, through reasonable API calls and adaptation, it ensures that low-version devices can also receive pushes normally.

  • Good scalability: Supports multiple message types (text, pictures, links, deep links, etc.) to facilitate subsequent expansion of business logic.

This article will combine actual project cases to gradually introduce how to build a set of message push solutions based on the Android platform to help developers deeply understand the principles, development processes and precautions of message push.

2. Introduction to related knowledge

2.1 Basic principles of message push

Push Notification technology refers to the server actively sending messages to the user terminal without the need for users to actively poll and query. Its basic principles usually include the following parts:

  • Application Server: Responsible for the generation and issuance of message content. The application server submits the message sending request to the message push platform.

  • Push platform: Such as Firebase Cloud Messaging (FCM), Huawei Push, Xiaomi Push, etc., it is responsible for receiving message requests from the application server and distributing them to the target device.

  • Client (Android application): Establish a connection with the push platform through the SDK, register and receive messages, and perform display processing after receiving the message.

2.2 Firebase Cloud Messaging(FCM)

Currently, Firebase Cloud Messaging provided by Google is a commonly used message push solution on Android. Compared with traditional GCM (Google Cloud Messaging), FCM has more functions and better compatibility. The main features of FCM include:

  • Cross-platform support: In addition to Android, it also supports various platforms such as iOS and Web.

  • Rich message types: Including notification messages and data messages. Notification messages are managed by the system, suitable for simple reminders; data messages are processed independently by the application for easy customization and extension.

  • High reliability: With the help of Google's infrastructure, it can ensure high reliability and real-time messaging.

2.3 Android Notification System

On Android, message notification mainly relies on the Notification mechanism, which involves the following important knowledge points:

  • Notification Channel: Starting from Android 8.0 (API Level 26), all notifications must belong to the specified channel, and users can manage each channel in the settings.

  • Notification Views (RemoteViews): Supports custom notification interface, which can display rich message content.

  • Front Desk Service Notification: Used to remind users that the application is running when it is running for a long time (for example, keep-alive when pushing the service background runs).

2.4 Android network communication basics

During the message push process, the communication between the client and the push platform depends on network communication technology. Common basic knowledge includes:

  • HTTP/HTTPS request: Application servers and push platforms (FCMs) usually interact with data through the HTTPS protocol.

  • WebSocket and long connection technology: Some self-built push solutions use long connections (such as Socket communication) for real-time message transmission.

  • JSON data parsing: Most push messages are encapsulated in JSON format, and it is necessary to master JSON parsing (such as using Gson, Jackson and other libraries).

2.5 Android life cycle management and background operation

In order to ensure that the push function can run normally in both the front and backend of the application, the following content needs to be understood:

  • Service and JobScheduler: Use Service or JobScheduler to implement background tasks to ensure that the application can receive pushes even when it is in the background.

  • Broadcast receiver: Use BroadcastReceiver to capture system network changes, device startup and other broadcasts to ensure that the push service is started in various scenarios.

  • Power saving and storing management: Understand the Doze mode and power saving strategy, optimize the wake-up strategy of push messages, and avoid power loss due to frequent wake-ups.

Ideas for project implementation

The implementation idea of ​​the entire Android message push project can be divided into the following steps:

3.1 Establishing an FCM service environment

  • Register a Firebase project: Create a new project in the Firebase console, bind an Android application, and download the configuration file ().

  • Add dependencies: Add FCM-related dependencies to the project, such as:firebase-messaging

3.2 Client Integration FCM SDK

  • Initialize the SDK: When the application starts, Firebase is initialized and a registered token is automatically generated to facilitate the server to identify the terminal device.

  • Custom message processing: Implement the class inherited from FirebaseMessagingService, and override the message reception and processing methods (such as onMessageReceived()).

3.3 Message display and notification management

  • Notification channel management: Create notification channels and classify notification management for Android 8.0 and above.

  • Custom notification styles: You can select the system default notification style, or you can use RemoteViews to build a custom notification interface.

  • Mixed message processing with data and notifications: Determine the message type based on business needs and select the system display and application custom processing method.

3.4 Backend services and message storage

  • Front and backend processing strategy: When the application is in the foreground, the message can be prompted through pop-up windows and Dialog; when in the background, it is displayed in the notification bar.

  • Message storage: Important messages can be stored in local databases or SharedPreferences for easier subsequent queries and synchronization management.

3.5 Security and compatibility

  • Authorization application: Ensure that the application declares necessary permissions such as INTERNET, ACCESS_NETWORK_STATE, etc., and at the same time, apply for notification permissions after Android 13 (POST_NOTIFICATIONS).

  • Compatibility testing: Test the stability and consistency of notification display and message reception under different manufacturers and different Android versions.

Based on the above ideas, the core of the entire project is to use the FCM platform to implement message dispatch, and then classify the received messages on the client, and display them to users in combination with the notification system, while ensuring that messages can be continuously accepted and corresponding feedback can be made in the application background.

4. Detailed code implementation

The following will provide an integrated code implementation example, including the configuration, message reception, notification creation and display of Firebase message service, and add detailed comments to the code to explain the role of each part. All codes are integrated for easy copying and use.

Notice

  • You need to complete the project registration and download it in the Firebase consoleFiles placed in the projectappIn the directory;

  • Services and permissions need to be configured correctly;

  • Google service plug-in needs to be integrated in the project.

/**
  * file name: 
  * Description: The main application portal is used to display received messages or perform other business logic processing.
  */
package ;
 
import ;
import ;
import ;
import ;
 
public class MainActivity extends AppCompatActivity {
 
    private static final String TAG = "MainActivity";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        (savedInstanceState);
        // Bind the main interface layout file        setContentView(.activity_main);
 
        // Initialize the Firebase message service and automatically handle token generation and message reception        initFirebase();
    }
 
    /**
      * Initialize Firebase, get the registered token, and subscribe to the topic
      */
    private void initFirebase() {
        // Get the registered token of the current device (can be used to display tests or send them to the server)        ().getToken()
            .addOnCompleteListener(task -> {
                if (!()) {
                    (TAG, "Failed to obtain the token", ());
                    return;
                }
                // Get the generated token                String token = ();
                (TAG, "Getted Token: " + token);
                // TODO: Upload the token to the server to facilitate accurate delivery of messages to the current device            });
 
        // Example: Subscribe to the "news" topic, and the message sent by the server to the topic will be pushed to the device        ().subscribeToTopic("news")
            .addOnCompleteListener(task -> {
                if (()){
                    (TAG, "Successfully subscribed to the 'news' topic");
                } else {
                    (TAG, "Subscribe to topic failed", ());
                }
            });
    }
}
<!--  -->
<manifest xmlns:andro
    package="">
 
    <!-- Required Permission Statement -->
    <uses-permission android:name="" />
    <uses-permission android:name=".ACCESS_NETWORK_STATE" />
    <!-- Android 13Systems above require dynamic application notification permission -->
    <uses-permission android:name=".POST_NOTIFICATIONS" />
 
    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher"
        android:theme="@style/AppTheme">
        
        <!-- hostActivitystatement -->
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="" />
                <category android:name="" />
            </intent-filter>
        </activity>
 
        <!-- Configure customizationFirebaseMessage Service -->
        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name=".MESSAGING_EVENT" />
            </intent-filter>
        </service>
    </application>
</manifest>
<!-- activity_main.xml: Application main interface layout example -->
<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp">
 
    <!-- Sample information display component -->
    <TextView
        android:
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to use message push example"
        android:textSize="20sp"
        android:textColor="@android:color/black" />
</LinearLayout>

5. Code interpretation

In the above code implementation, the functions of the main modules and methods are as follows:

5.1 MyFirebaseMessagingService Class

  • onNewToken(String token)
    effect:
    Called when Firebase generates a new token, which is used to identify the client device and can be uploaded to the application server for directed push.
    Note: In actual projects, the token upload logic needs to be implemented to ensure that the server can be associated with the device.

  • onMessageReceived(RemoteMessage remoteMessage)
    effect:
    Process all messages sent from the FCM, distinguishing between notification messages and custom data messages.
    Implementation details:

    • If the message contains a notification part, the sendNotification() method is called directly to display the notification;

    • If the message contains a portion of the data, try to parse the JSON data, extract custom titles and content, display notifications, or execute other business logic.

  • sendNotification(String title, String message)
    effect:
    Build and display system notifications, support notification channel management for Android 8.0 and above, click on notification and jump to MainActivity.
    Key points:

    • Use to build notification objects;

    • Use PendingIntent to set click action;

    • For Android O and above, you need to create a notification channel first.

5.2 MainActivity Class

  • onCreate(Bundle savedInstanceState)
    effect:
    The layout is loaded when the main interface is initialized, and the initFirebase() method is called to initialize the FCM-related logic.

  • initFirebase() method
    effect:

    • Get the FCM registration token of the current device;

    • Subscribing to a specified topic (such as "news") facilitates receiving group messages sent by the server.
      Note: The token can be uploaded to the server, and after the topic subscription is successful, the message sent by the server to the specified topic will be pushed to the device.

5.3 Configuration

  • Permission Statement
    effect:
    Allows applications to access the network, detect network status, and dynamically apply for notification permissions on Android 13 and above systems.

  • Service Configuration
    effect:
    Configure MyFirebaseMessagingService as Firebase message processing service, and its intent filter ensures that message events can be routed to the Service.

6. Project summary and reflection

6.1 Project implementation effect evaluation

advantage

  • Real-time push: With the help of the FCM platform, messages can be pushed to the device in real time and can be received regardless of the application in the foreground or backend.

  • Easy to expand: The code structure is clear, which can be easily expanded to support pushing of multiple message types (such as pictures, rich text, etc.).

  • Unified management notification channels: Follow Android 8.0+ notification channel specifications to facilitate user management and custom notification behavior.

Deficiencies and improvement directions

  • Network dependencies: Message push depends on the network environment. If the network is unstable, it may cause message delay.

  • Security and Privacy: The security of push data needs to be further considered. It is recommended to combine HTTPS encryption, Token verification and other security measures in actual projects.

  • Message display customization: Extended custom notification view to achieve more personalized message display effect and improve user experience.

6.2 Knowledge learned

During the implementation of this project, we have thoroughly studied and practiced the following key knowledge points:

  1. Firebase Cloud Messaging Basics: Including project registration, token acquisition, message reception and topic subscription.

  2. Android Notification System: Involves notification channels, the use of NotificationCompat, PendingIntent, and jump management after user clicks notifications.

  3. Service and background message processing: FirebaseMessagingService inheritance and message distribution logic enables applications to respond to pushes in real time in the front and backends.

  4. Network communication basics: Analysis and processing of data format (such as JSON) during message data transmission.

  5. Permissions and compatibility processing: Compatibility configuration is carried out for different Android versions (such as Android O and above requirements) to ensure the stable operation of the application.

6.3 The value of message push in actual applications

As an instant communication technology, message push has a wide range of application scenarios in actual projects, including but not limited to:

  • User interaction: Timely push order status, friend messages, etc. to improve user stickiness.

  • Marketing and promotion: Promote sales conversion through targeted promotion of discount information and event reminders.

  • System alarm: When an abnormality occurs in the system or there are important messages, push notifications to the user to ensure safety.

  • Content update: For news and information applications, real-time content updates are pushed to increase user access frequency.

6.4 Problems and solutions encountered in development

  • Token updates frequently
    Cause: Firebase will update the token in some cases. If the token upload is not processed correctly, the message push will fail.
    Solution: Upload the latest token in time in the onNewToken method, and check and synchronize the token information when the application starts.

  • Notify channel management issues
    Cause: Android 8.0 or above requires that all notifications must be bound to a specific channel. If the channel is not created, the message will not be displayed.
    Solution: Determine the system version before sending notifications, and create and configure notification channels if needed.

  • Message type mixing processing
    Reason: Including both notification parts and custom data in the same push can easily cause confusion in processing.
    Solution: Clearly distinguish and process different types of messages according to business needs, and use branch logic to process them separately if necessary.

6.5 Recommendations for follow-up improvements and extensions

  1. Custom notification interface
    Use RemoteViews to build a richer notification interface, such as multimedia display and expandable notifications, to achieve a better user interaction experience.

  2. Message statistics and logging
    Integrate data statistics module to record and analyze the behaviors of receiving, clicking, reading and other push messages, and optimize push strategies.

  3. Unified management of multi-platform messages
    Combined with iOS, Web and other platforms, a unified message push service is realized to facilitate cross-platform business logic coordination.

  4. Enhanced security mechanisms
    Consider adding data encryption and verification mechanisms to message transmission to ensure that the pushed data is protected from tampering or stealing during transmission.

  5. Deeply customized business logic
    For different business scenarios, such as order reminders, news updates, live chats, etc., more detailed message classification and processing strategies are implemented to improve user experience.

7. Project Summary and Prospect

This project introduces in detail how to implement message push on the Android platform, including FCM service integration, message reception and processing, notification display and back-end interaction, etc. Through detailed interpretation of key modules and code examples, developers can not only quickly build a complete message push system, but also deeply understand the principles and design ideas behind it.

In project practice, clear requirements analysis, perfect error handling and continuous performance optimization are all essential. In the future, with the continuous improvement of mobile device functions and the advancement of network technology, message push systems will usher in more innovations, such as combining machine learning to achieve intelligent push, more accurate user grouping and tag management, and deep integration with new technologies such as the Internet of Things.

I hope this article can provide valuable reference and practical guide for developers, helping you to efficiently implement and optimize message push functions in actual projects, and bring users a timely and rich information interaction experience.

8. Appendix: Development Environment and Tools

Development Environment

  • Android Studio Version: It is recommended to use the latest version to ensure compatibility with the latest Android API.

  • Minimum API version: According to project requirements, API 21 or above is generally recommended to ensure that most devices support FCM functions.

  • Test equipment: It is recommended to test in a variety of real machine and emulator environments to verify the performance of notifications on various Android versions.

Main dependency library

  • Firebase Cloud Messaging:rely:firebase-messagingImplement message push function.

  • Google Services plugin:ConfigurationFile to ensure normal communication with Firebase service.

  • Gson/JSON processing library: Used when parsing the custom data part of the push message.

Development and debugging tools

  • Logcat: Used to output debug logs, monitor token generation, message reception and error logs.

  • Firebase console: Manage push messages, test messages and data statistics.

  • Android Profiler: Used to detect the resource consumption and network communication efficiency of the background service.

The above is the detailed content of implementing the message push function on the Android platform. For more information about Android message push, please follow my other related articles!