Java Android App Development Course, Obtaining Smartphone Information

Getting Smartphone Information

Utilizing various information from smartphones in Android app development is very important. In this course, we will learn how to obtain smartphone information in an Android app.

1. Introduction to Context in Android

Context is an important class in Android that provides information about the application environment. All Android components (Activity, Service, etc.) interact with each other through Context. To obtain smartphone information, Context must be utilized.

2. Types of Smartphone Information

There are various types of information that can be obtained from a smartphone. The main information includes:

  • Device Model
  • Manufacturer
  • Android Version
  • Status Bar and Network Information

3. Setting Required Permissions

To obtain certain information in Android, permissions must be added to the app’s manifest file. For example, to check the network status, the following permissions are needed:

        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        <uses-permission android:name="android.permission.INTERNET"/>
    

4. Obtaining Smartphone Information with Java

4.1 Device Model and Manufacturer Information

To get the device model and manufacturer information, use the Build class. Here is an example code:

        import android.os.Build;

        String deviceModel = Build.MODEL; // Device Model
        String manufacturer = Build.MANUFACTURER; // Manufacturer
    

4.2 Android Version Information

Android version information can be accessed through the Build.VERSION class. For example, you can obtain the current Android version as follows:

        String androidVersion = Build.VERSION.RELEASE; // Android Version
    

4.3 Checking Network Status

To check the network status, use ConnectivityManager. The following code is an example that checks the status of the currently connected network:

        import android.content.Context;
        import android.net.ConnectivityManager;
        import android.net.NetworkInfo;

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    

5. Implementing Example App

Let’s implement a simple example app that displays smartphone information. This app will show the device model, manufacturer, and Android version information on the screen.

5.1 XML Layout File

First, create the res/layout/activity_main.xml file. Add a TextView as follows:

        <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/device_info"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Device Information"
                android:textSize="18sp"/>

        </RelativeLayout>
    

5.2 MainActivity.java

Next, modify the MainActivity.java file to display the information on the screen:

        import android.app.Activity;
        import android.os.Bundle;
        import android.widget.TextView;
        import android.os.Build;

        public class MainActivity extends Activity {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                TextView deviceInfoTextView = findViewById(R.id.device_info);
                String deviceModel = Build.MODEL;
                String manufacturer = Build.MANUFACTURER;
                String androidVersion = Build.VERSION.RELEASE;

                String deviceInfo = "Manufacturer: " + manufacturer + 
                                    "\nModel: " + deviceModel + 
                                    "\nAndroid Version: " + androidVersion;

                deviceInfoTextView.setText(deviceInfo);
            }
        }
    

6. Conclusion

Through this, we have created a simple smartphone information checker app. Such information can provide value to users and is essential for implementing various features in an app. To delve deeper, it is also good to learn how to gather more information through APIs.

7. Next Course Preview

In the next course, we will learn how to receive external information using Google APIs. The world of Android app development is vast, and we will continue to learn various technologies in the future.

Java Android App Development Course, Sound and Vibration Notifications

Hello! Today, we will learn how to implement a notification feature using sound and vibration in an Android app development course utilizing Java. Notifications that we commonly use are one of the means of conveying important information to users by the app. In this course, we will detail step by step how to send notifications to users utilizing sound and vibration.

1. Importance of Notifications

Notifications help users recognize important events occurring in the app. For instance, informing users when an email or message arrives, or when a specific action is completed in the app. Such notifications can attract the user’s attention not only through visual elements but also through sound and vibration.

2. Project Setup

First, you need to create a new Android project. Open Android Studio, select File > New > New Project, and choose Empty Activity. After deciding on the project name and package name and completing the necessary settings, a new project will be created.

2.1 Gradle Setup

No special libraries are required to implement notifications, but it is recommended to use the latest Android SDK and Gradle. Open the build.gradle file of the project and verify that it contains the following content.

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.1.0'
    }
}
allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

3. Understanding the Concept of Notification

Notifications are messages that provide important information to users on Android. Starting from Android 8.0 (API level 26), a notification channel must be set up in order to send notifications. The notification channel offers users a way to distinguish between types of notifications. Each channel can control sound, vibration, and priority through user settings.

4. Code Implementation

Now let’s get down to implementing notifications including sound and vibration in Android. Below is a detailed code example for creating a notification and setting sound and vibration.

4.1 Setting Up AndroidManifest.xml

First, you need to add the necessary permissions in the AndroidManifest.xml file. Add the VIBRATE permission to use vibration.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.notificationexample">

    <uses-permission android:name="android.permission.VIBRATE"/>

    <application...>
        ...
    </application>
</manifest>

4.2 Implementing the Main Activity

Modify the main activity to set it up to receive notifications. Below is the MainActivity.java that includes the code to create notifications.

package com.example.notificationexample;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    // Notification Channel ID
    private static final String CHANNEL_ID = "exampleChannel";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button notifyButton = findViewById(R.id.notify_button);
        notifyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createNotification();
            }
        });

        createNotificationChannel();
    }

    private void createNotificationChannel() {
        // Notification channels are required for Android 8.0 and above
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Example Channel";
            String description = "Channel for example notifications";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    private void createNotification() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("Notification Title")
                .setContentText("This is a notification with sound and vibration.")
                .setAutoCancel(true)
                .setPriority(Notification.PRIORITY_HIGH)
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setVibrate(new long[]{0, 1000, 500, 1000});

        notificationManager.notify(1, builder.build());

        // Activate vibration feature
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        if (vibrator != null) {
            vibrator.vibrate(1000); // Vibrate for 1 second
        }
    }
}

4.3 Setting Up the XML Layout File

Add a button in the activity_main.xml layout file to allow for notification creation.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <Button
        android:id="@+id/notify_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send Notification"
        android:layout_centerInParent="true"/>

</RelativeLayout>

5. Running and Testing the App

If all settings are completed, run the app on an emulator or a real device. When you click the “Send Notification” button, a notification will appear with sound and vibration. This completes the implementation of a basic notification system. Sound and vibration can be varied by adjusting their respective types and lengths.

5.1 Additional Notification Settings

You can freely adjust the title, content, sound, and vibration pattern of notifications to provide notifications that meet user needs. For example, you can create multiple notification channels tailored to various situations and apply different settings to each channel.

6. Conclusion

In this course, we learned how to implement a notification feature integrating sound and vibration using Java and Android. Notifications play a crucial role in communication with app users, effectively capturing the user’s attention through sound and vibration. Now, you too can use this feature to develop more useful Android apps. We look forward to more useful Android development courses in the future!

Thank you!

Java Android App Development Course, Linear Layout – LinearLayout

Java Android App Development Course: Linear Layout – LinearLayout

In Android app development, there are various components that make up the user interface (UI), among which LinearLayout is one of the most basic and important layouts. LinearLayout provides the functionality to arrange child views in a linear fashion, either horizontally or vertically. In this course, we will explain the concept, usage, attributes, and examples of LinearLayout in detail.

1. Understanding LinearLayout

LinearLayout is a view group that allows you to arrange child views in a single row. By default, it allows aligning child views in two directions: horizontal and vertical. This allows for quick and easy configuration of simple layouts.

1.1. Direction of LinearLayout

  • Vertical Direction: Child views are arranged from top to bottom.
  • Horizontal Direction: Child views are arranged from left to right.

1.2. Components

LinearLayout has the following characteristics:

  • orientation: Sets the direction of the LinearLayout. (vertical/horizontal)
  • layout_width: Sets the width of the LinearLayout. (match_parent/wrap_content)
  • layout_height: Sets the height of the LinearLayout. (match_parent/wrap_content)
  • gravity: Controls the position of child views.
  • padding: Sets the space between the LinearLayout and the child views.
  • layout_margin: Sets the space between child views and other elements.

2. How to Use LinearLayout

To use LinearLayout, define it in the XML layout file and add other views inside it. The basic structure of a LinearLayout is as follows.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello!" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me!" />

</LinearLayout>

2.1. Example of LinearLayout Settings

Below is an example of a LinearLayout set in a vertical direction. In this example, we will create a simple app using basic UI elements, namely TextView and Button.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, LinearLayout example!" 
        android:textSize="24sp"
        android:layout_gravity="center"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click!"
        android:layout_gravity="center"/>

</LinearLayout>

2.2. Horizontal Example

LinearLayout can also be set in horizontal direction. The following code is an example of arranging a button and a text view horizontally.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button: " 
        android:textSize="18sp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click"/>

</LinearLayout>

3. Key Attributes of LinearLayout

Now, let’s explain the key attributes you need to know when using LinearLayout.

3.1. orientation

The orientation attribute sets the direction of the LinearLayout. The default value is vertical direction.

android:orientation="vertical"
android:orientation="horizontal"

3.2. layout_gravity

The layout_gravity attribute sets the position of child views. By default, child views will take the full width or height of the LinearLayout.

android:layout_gravity="center"

3.3. weight

The weight attribute is very useful for setting the proportion of child views. This allows you to adjust the space that child views occupy within the LinearLayout.

Below is an example where two buttons are used, sharing an equal proportion.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="First Button"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Second Button"/>

</LinearLayout>

4. Example Application Using LinearLayout

Now, let’s create a simple app that uses LinearLayout. The following example shows an app where the user inputs their name, and upon clicking a button, a welcome message is displayed.

4.1. XML Layout File (activity_main.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <EditText
        android:id="@+id/editTextName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name"/>

    <Button
        android:id="@+id/buttonGreet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Greet"/>

    <TextView
        android:id="@+id/textViewGreeting"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="24sp"/>

</LinearLayout>

4.2. Java Code (MainActivity.java)

package com.example.helloapp;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText editTextName;
    private Button buttonGreet;
    private TextView textViewGreeting;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextName = findViewById(R.id.editTextName);
        buttonGreet = findViewById(R.id.buttonGreet);
        textViewGreeting = findViewById(R.id.textViewGreeting);

        buttonGreet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = editTextName.getText().toString();
                String greeting = "Hello, " + name + "!";
                textViewGreeting.setText(greeting);
            }
        });
    }
}

5. Precautions When Using LinearLayout

  • Be cautious not to include too many child views in LinearLayout as it may impact performance. Instead, consider other layouts such as ConstraintLayout.
  • When using layout_weight, the width or height of child views should be set to ‘0dp’.
  • Ensure that the layout properties of views are set correctly to achieve the desired UI results.

6. Conclusion

LinearLayout is one of the most basic yet very useful layouts among Android UI components. In this course, we explored the concept, usage, key attributes, and examples related to LinearLayout. You can effectively configure simple user interfaces using LinearLayout. Furthermore, you can use it alongside various layout options to create more complex and sophisticated UIs.

Now, try creating your own app using LinearLayout! It would be great to practice by combining various UI elements and layout properties.

Java Android App Development Course, Understanding Services

In Android app development, ‘services’ are often an overlooked but important component. Services are designed to perform tasks that need to run for a long time in the background, without a user interface (UI). In this course, we will explore the concept, types, usage, exceptions, and real examples of Android services to understand how they contribute to Android app development.

1. What is a Service?

A service is one of the components of an Android application that performs tasks in the background without user interaction. For example, tasks such as playing music, downloading files, and network communication can be handled by a service. Services can continue to perform tasks even when the user is not using the application.

2. Types of Services

Android services are classified into three types:

  • Started Service: A service that is started within the application and runs continuously until terminated by the system. For example, a music player application can utilize a service while music is playing.
  • Bound Service: A service that is bound to another component (e.g., an Activity) and shares tasks. A bound service is useful when interaction with clients is needed.
  • IntentService: A service that handles requested tasks in the background and automatically stops itself once the tasks are completed. This feature is designed to perform tasks on a single thread.

3. Creating a Service

To create a service, you need to define a class and implement methods to start and stop the service. Here is how to create a basic service:

public class MyService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        // Work to be done when the service is created
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Work to be done when the service starts
        return START_STICKY; // Allows the service to restart even after it has been stopped.
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Called when binding to the service. Usually returns null.
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Perform cleanup tasks when the service is destroyed
    }
}

4. Registering a Service

To use a service, you must register it in the Manifest file. Here is an example of service registration:

<service android:name=".MyService"></service>

5. Starting a Service

To start a service, you need to invoke it via an Intent. Here is an example of starting a service:

Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);

6. Stopping a Service

Here is how to stop a service:

stopService(serviceIntent);

7. Using a Bound Service

A bound service helps share specific tasks with an activity. Here is how to implement a bound service:

public class MyBoundService extends Service {
    private final IBinder binder = new LocalBinder();

    class LocalBinder extends Binder {
        MyBoundService getService() {
            return MyBoundService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public String getGreeting() {
        return "Hello from MyBoundService!";
    }
}

An example of an activity calling the bound service is as follows:

private MyBoundService boundService;
private boolean isBound = false;

private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        MyBoundService.LocalBinder binder = (MyBoundService.LocalBinder) service;
        boundService = binder.getService();
        isBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        isBound = false;
    }
};

// Binding the service
Intent intent = new Intent(this, MyBoundService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);

8. Using IntentService

IntentService is a useful component for handling long-running tasks in the background. IntentService processes tasks asynchronously and automatically shuts down when the tasks are complete. Here is an example of implementing IntentService:

public class MyIntentService extends IntentService {
    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        // Write task handling logic here
    }
}

Here is how to call the service:

Intent intent = new Intent(this, MyIntentService.class);
startService(intent);

9. Service Lifecycle

A service goes through the following states and follows a lifecycle:

  • onCreate(): Called when the service is created.
  • onStartCommand(): Called when the service is started.
  • onBind(): Called when the service is bound.
  • onDestroy(): Called when the service is destroyed.

Understanding the service lifecycle is crucial for providing a smooth user experience.

10. Service Optimization

When using services, consider the following optimization tips:

  • Avoid unnecessary use of services. Consider using threads where possible.
  • Regularly check the necessity of services.
  • Properly clean up resources after the service has been terminated.

11. Conclusion

In this course, we explored the concept, types, lifecycle, and implementation methods of services in Android app development using Java. Services are an important element that can enhance user experience and add functionality to applications. Make good use of the advantages of services in real applications to develop even more advanced apps.

If you have any questions or comments, please feel free to leave them in the comments. Thank you!

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!