Java Android App Development Course, Integrating with Basic Android Apps

1. Introduction

In today’s mobile environment, the Android platform is one of the most widely used operating systems. In particular, using the Java language to develop apps is a familiar approach for many developers. In this course, we will start from the basics of app development through integration with basic Android apps and take it a step further to implement various features. Through this course, you will understand the interaction between Android apps and basic apps (e.g., contacts, camera, etc.) and develop the ability to implement them yourself.

2. Setting Up the Android App Development Environment

To develop Android apps, you first need to set up the development environment. Using Android Studio provides many convenient tools and features. Below are the installation steps for Android Studio.

  1. Download Android Studio: Download from the official Google site.
  2. Installation: Follow the installation wizard.
  3. SDK Installation: The necessary SDKs and tools will be installed automatically.
  4. Creating a Project: Click on ‘New Project’ to create a new Android project.

3. Understanding Android Basic Apps

Android has several types of basic apps. These apps provide functionalities that developers can easily use without the need for external libraries. For example, there are contacts apps, camera apps, maps apps, etc. In this section, we will use an example connected to the contacts app to explore the functionalities of basic apps.

4. Integrating with the Contacts App

We will implement a feature that retrieves contact information by integrating with the contacts app. The following are the steps to implement this feature.

4.1. Requesting Permissions

To access the contacts, you need to request permission from the user. Add the following permission to the AndroidManifest.xml file.

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

4.2. Retrieving Contact Information

Now, open the MainActivity.java file and write the code to retrieve contact information.

                
                import android.Manifest;
                import android.content.ContentResolver;
                import android.content.pm.PackageManager;
                import android.database.Cursor;
                import android.net.Uri;
                import android.os.Bundle;
                import android.provider.ContactsContract;
                import android.view.View;
                import android.widget.Button;
                import android.widget.TextView;
                import androidx.annotation.NonNull;
                import androidx.appcompat.app.AppCompatActivity;
                import androidx.core.app.ActivityCompat;

                public class MainActivity extends AppCompatActivity {
                    private static final int REQUEST_CODE_CONTACT = 1;
                    private TextView textView;

                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                        
                        textView = findViewById(R.id.textView);
                        Button button = findViewById(R.id.button);
                        
                        button.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                checkPermission();
                            }
                        });
                    }

                    private void checkPermission() {
                        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_CODE_CONTACT);
                        } else {
                            getContacts();
                        }
                    }

                    private void getContacts() {
                        ContentResolver resolver = getContentResolver();
                        Uri uri = ContactsContract.Contacts.CONTENT_URI;
                        Cursor cursor = resolver.query(uri, null, null, null, null);
                        
                        StringBuilder contactsList = new StringBuilder();
                        
                        while (cursor.moveToNext()) {
                            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                            contactsList.append(name).append("\n");
                        }
                        cursor.close();
                        textView.setText(contactsList.toString());
                    }

                    @Override
                    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
                        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                        if (requestCode == REQUEST_CODE_CONTACT && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                            getContacts();
                        }
                    }
                }
                
            

4.3. Building the UI

Open the activity_main.xml file and build the UI. You will add a Button and a TextView by default.

                
                <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">
                    <Button
                        android:id="@+id/button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Get Contacts" />

                    <TextView
                        android:id="@+id/textView"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" />
                </LinearLayout>
                
            

4.4. Running the App

Now, run the project. When you click the ‘Get Contacts’ button, the list of contacts will be displayed in the TextView. If a permission request dialog appears, you must click allow to retrieve contact information.

5. Integrating with the Camera App

Next, we will implement a feature to take a photo by integrating with the camera app. Integrating with the camera is also a great example of integration between basic apps.

5.1. Requesting Permissions

The method for requesting permissions to access the camera is similar to that of the contacts app. Add the following to the AndroidManifest.xml.

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

5.2. Taking a Photo

Add the function for taking a photo in the MainActivity.java file.

                
                import android.content.Intent;
                import android.graphics.Bitmap;
                import android.net.Uri;
                import android.os.Bundle;
                import android.provider.MediaStore;
                import android.widget.Button;
                import android.widget.ImageView;
                import androidx.appcompat.app.AppCompatActivity;

                public class MainActivity extends AppCompatActivity {
                    private static final int REQUEST_IMAGE_CAPTURE = 1;
                    private ImageView imageView;

                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                        
                        Button button = findViewById(R.id.button);
                        imageView = findViewById(R.id.imageView);
                        
                        button.setOnClickListener(view -> {
                            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                            }
                        });
                    }

                    @Override
                    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                        super.onActivityResult(requestCode, resultCode, data);
                        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
                            Bundle extras = data.getExtras();
                            Bitmap imageBitmap = (Bitmap) extras.get("data");
                            imageView.setImageBitmap(imageBitmap);
                        }
                    }
                }
                
            

5.3. Building the UI

Add an ImageView in the activity_main.xml file to display the captured photo.

                
                <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">
                    <Button
                        android:id="@+id/button"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Take Photo" />

                    <ImageView
                        android:id="@+id/imageView"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" />
                </LinearLayout>
                
            

5.4. Running the App

Now run the program and click the ‘Take Photo’ button. If it works correctly, the camera will launch, and after taking the photo, the result will be displayed in the image view.

6. Conclusion

In this course, we learned how to integrate with basic Android apps using Java. Through the integration of contacts and camera apps, we explored how to utilize the functionalities of basic apps in app development. Based on this example, you can expand your own app functionalities and try various forms of integration. Continue to learn and practice Android app development to further your skills!

Java Android App Development Course, Understanding System Status

Hello! In this course, we will explore one of the very important topics in Android app development: how to understand the system status. Understanding system status in Android development is an essential element for optimizing app performance, improving user experience, and debugging. Through this course, we will learn how to collect system information and how to improve the app based on this information.

1. What is system status?

System status refers to various information and attributes that the current device possesses. This includes CPU usage, memory usage, battery status, network status, and more. This information provides important hints about how the app operates and how to manage resources efficiently.

2. Checking system status in Android

In Android, you can check system status through various APIs. In this section, we will learn how to retrieve the main system status information in Android.

2.1. Checking battery status

To check the battery status, you can use the BatteryManager class. Below is an example code for checking the battery status.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

public class BatteryStatusReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        float batteryPct = level / (float)scale * 100;

        // Print remaining battery
        System.out.println("Current battery level: " + batteryPct + "%");
    }
}

The above code creates a receiver that receives the battery status. The onReceive method is called every time the battery status changes, outputting the current battery level. To register this receiver, you can use the following code.

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

2.2. Checking memory status

To measure memory usage, Android utilizes the ActivityManager class. Here is a code example to check current memory usage.

ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);

long totalMem = memoryInfo.totalMem;
long availMem = memoryInfo.availMem;

// Print memory status
System.out.println("Total memory: " + totalMem + " bytes, Available memory: " + availMem + " bytes");

This code outputs the current total memory and available memory. This provides insights into memory management for the app.

2.3. Checking CPU usage

To check CPU usage, you can use methods provided by the Debug class. Here is a simple way to measure CPU usage.

import android.os.Debug;

// Print CPU usage
Debug.MemoryInfo memoryInfo = new Debug.MemoryInfo();
Debug.getMemoryInfo(memoryInfo);

int totalPss = memoryInfo.getTotalPss();
System.out.println("Total PSS: " + totalPss + " KB");

Through this, you can get information about the current app’s memory usage and CPU usage, contributing to performance optimization.

3. Optimizing resource usage based on system status

After understanding the system status, you can optimize the app’s resource usage based on this. Here are a few optimization methods.

3.1. Appropriate process termination

When the system memory is low, you can ensure system stability by terminating unnecessary processes. You can manage running processes using ActivityManager.

activityManager.killBackgroundProcesses("com.example.app");

3.2. Optimizing battery usage

To minimize battery usage, it is essential to adjust the frequency of background tasks appropriately and stop unnecessary tasks. For example, you can reduce network requests to a minimum or adjust to not use GPS continuously.

3.3. Providing notifications to users

By providing notifications to users based on system status, you can improve the user experience. For example, if the battery level falls below a certain threshold, you can notify the user about switching to battery-saving mode.

if (batteryPct < 20) {
    // Notify the user about battery-saving mode
}

4. Summary

In this course, we learned how to understand system status in Android app development and techniques for optimizing resources based on this understanding. We covered various methods to monitor battery, memory, CPU usage, etc., to enhance app performance and improve user experience. Developing apps based on this system information will lead to more stable and efficient applications.

Now you have the ability to create better apps by understanding and optimizing system status in Android app development. If you have further questions or want to cover more in-depth topics, we recommend referring to additional materials. Thank you!

Java Android App Development Course, Creating the Stopwatch Feature of a Clock App

For modern smartphone users, a clock app is an indispensable tool.
Consequently, many developers are creating clock apps and adding various features.
In this tutorial, we will explore in detail how to implement a stopwatch function while developing an Android app using Java.

1. Setting Up the Development Environment

To develop a stopwatch app, you need Android Studio and a Java development environment.
Follow the steps below to set up the development environment.

  1. Download and Install Android Studio:
    Android Studio is the officially supported Android development tool.
    Download the latest version from the [Android Studio Download Page](https://developer.android.com/studio) and install it.
  2. Create a New Project:
    Launch Android Studio and select “New Project,” then choose “Empty Activity.”
    Set the project name to “StopwatchApp” and select Java.
  3. Gradle Setup:
    Use Gradle builds to add the necessary libraries and set the SDK version.
    Set `compileSdkVersion` and `targetSdkVersion` appropriately in the `build.gradle` file.

2. Designing the UI

Now, let’s design the UI of the stopwatch. In Android, we define layouts using XML.
Open the `activity_main.xml` file and write the code as shown below.

<?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/txtTimer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="00:00:00"
        android:textSize="48sp"
        android:layout_centerInParent="true"/>

    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start"
        android:layout_below="@id/txtTimer"
        android:layout_marginTop="20dp"
        android:layout_alignParentStart="true"/>

    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop"
        android:layout_below="@id/txtTimer"
        android:layout_marginTop="20dp"
        android:layout_toEndOf="@id/btnStart"
        android:layout_marginStart="20dp"/>

    <Button
        android:id="@+id/btnReset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Reset"
        android:layout_below="@id/txtTimer"
        android:layout_marginTop="20dp"
        android:layout_toEndOf="@id/btnStop"
        android:layout_marginStart="20dp"/>

</RelativeLayout>

The UI includes a `TextView` that displays the time in the center and three buttons (Start, Stop, Reset).
These buttons control the stopwatch’s functionality.

3. Implementing Stopwatch Functionality

Now that the UI is ready, it’s time to implement the watch functionality.
Open the `MainActivity.java` file and write the code as follows.

package com.example.stopwatchapp;

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

public class MainActivity extends AppCompatActivity {
    private TextView txtTimer;
    private Button btnStart, btnStop, btnReset;
    private long startTime = 0L;
    private boolean isRunning = false;
    private final Handler handler = new Handler();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        txtTimer = findViewById(R.id.txtTimer);
        btnStart = findViewById(R.id.btnStart);
        btnStop = findViewById(R.id.btnStop);
        btnReset = findViewById(R.id.btnReset);
        
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isRunning) {
                    startTime = SystemClock.elapsedRealtime();
                    handler.postDelayed(runnable, 0);
                    isRunning = true;
                }
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isRunning) {
                    handler.removeCallbacks(runnable);
                    isRunning = false;
                }
            }
        });

        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.removeCallbacks(runnable);
                txtTimer.setText("00:00:00");
                isRunning = false;
            }
        });
    }

    private final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            long elapsedMillis = SystemClock.elapsedRealtime() - startTime;
            int seconds = (int) (elapsedMillis / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;
            int hours = minutes / 60;
            minutes = minutes % 60;

            txtTimer.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
            handler.postDelayed(this, 1000);
        }
    };
}

The above code contains the basic functionality of the stopwatch.
It uses a `Handler` to periodically update the elapsed time.

  • Start Button: Starts the stopwatch and begins counting time.
  • Stop Button: Stops the stopwatch and retains the current time.
  • Reset Button: Resets the stopwatch and displays the time as “00:00:00”.

4. Testing the App

Now it’s time to test the stopwatch app. Click the “Run” button in Android Studio to
launch the app in the emulator. Click the buttons to verify that the stopwatch functionality works correctly.
It is important to test various scenarios to ensure all features operate seamlessly.

5. Implementing Additional Features

In addition to the basic stopwatch functionality, you might consider adding extra features to enhance the user experience.
For example, think about adding lap functionality, notification sounds, or user settings.

  1. Lap Functionality:
    Add a feature that allows users to record elapsed times for multiple laps.
  2. Sound Notifications:
    Provide feedback by sounding alerts when users start and stop the stopwatch.
  3. Theme Settings:
    Offer users the option to change the colors or fonts of the app.

These features can improve the quality of the app and enhance user satisfaction.

6. Conclusion

In this tutorial, you learned how to develop an Android stopwatch app using Java. I hope that setting up the development environment,
designing the UI, and implementing functionality provided a foundation in Android app development.
I encourage you to add more features or continue to evolve your app in your own style.

© 2023 Java Android App Development Course, All Rights Reserved.

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!