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!