Java Android App Development Course, Receive Notifications from Server

In Android app development, communication with the server is a very important element, and the ability to deliver information from the server to the client can greatly enhance user experience. In this course, we will explain in detail how to receive notifications sent from the server in an Android app using Java. In this process, we will implement the push notification feature using FCM (Firebase Cloud Messaging).

1. Introduction to FCM (Firebase Cloud Messaging)

FCM is a service provided by Google that is used to deliver push notifications to Android, iOS, and web applications. Through this service, developers can send information even when the user is not running the app. FCM is easy to use and provides a variety of features, which is why it is used in many apps.

2. Setting up FCM

2.1. Creating a Firebase Project

To use FCM, you first need to create a Firebase project.

  1. Log in to the Firebase console (https://console.firebase.google.com/).
  2. Create a new project and enter the project name.
  3. After setting up additional options such as Google Analytics, create the project.

2.2. Registering the Android App

Once the project is created, register the Android app in the Firebase project.

  1. Go to Project Settings in the Firebase console.
  2. Click on the Android icon to register the app.
  3. Enter the package name of the app and also add the SHA-1 certificate fingerprint. (Both debug and release certificates)
  4. Download the google-services.json file and place it in the app folder of the Android project.

2.3. Configuring Gradle

Edit the build.gradle file for basic dependency settings.

dependencies {
    implementation 'com.google.firebase:firebase-messaging:23.0.0'
}

Add the Google services plugin to the project-level build.gradle file.

buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

2.4. Configuring AndroidManifest.xml

Add the necessary permissions for Firebase in the AndroidManifest.xml file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.pushnotification">
    
    <application 
        ... >
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="default_channel">
        </meta-data>

        <service
            android:name=".MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
    </application>
</manifest>

3. Implementing Server Code

To send notifications using FCM from the server, we will introduce an example of a Node.js server using the Firebase Admin SDK.

3.1. Setting up Node.js Environment

After installing Node.js, install the Firebase Admin SDK.

npm install firebase-admin

3.2. Writing Server Code

const admin = require("firebase-admin");

// Path to Firebase service account key JSON file
const serviceAccount = require("./path/to/serviceAccountKey.json");

// Firebase initialization
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

// Function to send notifications
function sendNotification(token, message) {
    const payload = {
        notification: {
            title: message.title,
            body: message.body,
        },
    };

    admin
        .messaging()
        .sendToDevice(token, payload)
        .then((response) => {
            console.log("Successfully sent message:", response);
        })
        .catch((error) => {
            console.log("Error sending message:", error);
        });
}

// Client device's token and message content
const registrationToken = "Device's registration token";
const message = {
    title: "Push Notification Title",
    body: "This is the body of the push notification.",
};

// Sending notification
sendNotification(registrationToken, message);

4. Implementing Android Client

4.1. Extending FirebaseMessagingService

To receive push notifications, create a class that extends FirebaseMessagingService.

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import android.util.Log;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // Handle received notification
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            // Call method to display notification
            showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }
    }

    private void showNotification(String title, String messageBody) {
        // Implement code to display notification using NotificationCompat.Builder
    }

    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);
        // Implement code to send the new token to the server
    }
}

4.2. Displaying Notifications

To display notifications, implement a method to create and show notifications using NotificationCompat.Builder.

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;

private void showNotification(String title, String messageBody) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    String channelId = "default_channel";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentText(messageBody)
            .setSmallIcon(R.drawable.ic_stat_ic_notification);

    notificationManager.notify(0, notificationBuilder.build());
}

5. Testing and Debugging

If you have completed all configurations and code, it is now time to conduct a real test. Run the server and try sending a notification using the registration token. Check if the notification is properly received on the client app.

5.1. Checking Receipt of Notifications

If a notification is received, verify that a push notification appears at the top of the app and that a specific activity is executed when the notification is clicked.

5.2. Troubleshooting

If notifications are not being received, check the following:

  • Check if the FCM registration token is valid.
  • Check if the Firebase project settings are correct.
  • Ensure that the necessary permissions and services are added in AndroidManifest.xml.

6. Conclusion

In this course, we learned how to receive notifications sent from the server in an Android app using Java. We confirmed that we can easily implement push notifications using Firebase Cloud Messaging. Consider the potential to expand by adding various features needed for actual applications.

In the future, we will cover various FCM features such as customizing notifications, grouping, and delayed delivery, so please stay tuned. Thank you!