kotlin android app development course, app configuration file analysis

Author: [Your Name]

Date: [Date]

Introduction

To develop an Android app, it is essential to understand and utilize various configuration files. In this tutorial, we will analyze the roles and contents of several important configuration files for Android app development.
Kotlin is a highly effective language for managing these files while providing both productivity and stability.
This article aims to clarify the basic structure of an Android app and explore the features and content of each configuration file in-depth.

1. Basic Components of an Android App

Android apps are composed of several components, each serving a specific function. The commonly used configuration files primarily include the following:

  • AndroidManifest.xml
  • build.gradle
  • res folder (Resource files)
  • src folder (Code files)

These files provide the essential information required for the Android app to run, and we will examine the structure and roles of each file one by one.

2. AndroidManifest.xml

AndroidManifest.xml file is the core configuration file for all Android apps.
This file includes various information such as app components, permissions, and API level, enabling the Android system to execute the app correctly.

2.1. Key Attributes

package: Defines the package name of the app, typically following the reverse order of the domain.
permissions: Specifies the permissions that the app will require. For example, to access the internet, one must add <uses-permission android:name="android.permission.INTERNET"/>.
activity: Defines the activities of the app and describes how each activity will operate.

Example Code


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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>
</manifest>
            

3. build.gradle

Android projects utilize Gradle to manage the build process.
The build.gradle file is a critical file that handles project dependencies, SDK version settings, plugins, and more.

3.1. Key Sections

android: Defines the basic properties of the app, such as the target SDK version and minimum SDK version.
dependencies: Manages the libraries and modules that the app depends on.
For instance, to use Kotlin coroutines, one must add implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9".

Example Code


apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation "androidx.appcompat:appcompat:1.2.0"
    implementation "com.google.android.material:material:1.2.1"
}
            

4. Resource Folder (res)

The res folder is a directory that manages various resources such as images, layouts, and strings.
This folder organizes resources in a structured manner for easy access.

4.1. Key Folders

  • drawable: Stores image files.
  • layout: Contains UI layout files.
  • values: Stores various values like strings, colors, styles, etc.

Example Code

Layout file example (activity_main.xml):


<?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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/welcome_message" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_text" />

</LinearLayout>
            

5. Code Folder (src)

The src folder is where the Kotlin code that implements the app’s business logic is stored.
It includes each activity, fragment, and other classes, making it crucial to understand the package structure.

5.1. Basic Structure

– Each activity must inherit from the Activity class and is typically controlled by screen units.
– Fragments can be combined with related UI components to construct more efficient screens.

Example Code

Main activity example (MainActivity.kt):


package com.example.myapp

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
            

6. The Importance of Analyzing Configuration Files

Analyzing and understanding configuration files is fundamental to Android app development.
Each file directly impacts the app’s policies and behaviors, user interfaces, and functions.
Therefore, it is essential to thoroughly analyze and comprehend these files before developing the app.

This concludes our analysis of the main configuration files for Android apps using Kotlin.
I hope this deepens your understanding of each file’s role and assists you in developing excellent apps.

Thank you!

KOTLIN ANDROID APP DEVELOPMENT COURSE, ACTIVITY CONTROL

This course provides an in-depth explanation and practical examples on how to control activities when developing Android apps using Kotlin.

1. What is an Activity?

An activity is a basic component that constitutes the UI of an Android app. Each activity represents a single screen that interacts with the user, and multiple activities are used to implement the app’s functionality.

For example, a login screen, main screen, settings screen, etc., can each be composed of independent activities. Each activity has a lifecycle, which plays an important role in managing state changes in the app.

2. Activity Lifecycle

The lifecycle of an activity consists of the following main methods:

  • onCreate(): Called when the activity is created. It is used to initialize the UI and set up necessary data and resources.
  • onStart(): Called when the activity starts to become visible to the user.
  • onResume(): Called when the activity comes to the foreground. This is where interaction with the user can begin.
  • onPause(): Called when the current activity is paused before another activity is started. This is where necessary data saving tasks are performed.
  • onStop(): Called when the activity is no longer visible.
  • onDestroy(): Called when the activity is finished. This is where resource release tasks can be performed.

By appropriately utilizing these lifecycle methods, you can effectively manage the state of the app.

3. Creating a Basic Activity

Now, let’s create a simple Android app. We will look at how to create a basic activity using Kotlin.

3.1 Creating a Project

Open Android Studio and create a new project. Choose Kotlin as the programming language and select the basic template of Empty Activity. We’ll set the project name as HelloWorld.

3.2 Writing Activity Code


                package com.example.helloworld

                import android.os.Bundle
                import androidx.appcompat.app.AppCompatActivity

                class MainActivity : AppCompatActivity() {
                    override fun onCreate(savedInstanceState: Bundle?) {
                        super.onCreate(savedInstanceState)
                        setContentView(R.layout.activity_main)
                    }

                    override fun onStart() {
                        super.onStart()
                        // Actions to perform when the activity starts
                    }

                    override fun onResume() {
                        super.onResume()
                        // Actions to perform when the activity is in the foreground
                    }

                    override fun onPause() {
                        super.onPause()
                        // Actions to perform when the activity is paused
                    }

                    override fun onStop() {
                        super.onStop()
                        // Actions to perform when the activity is no longer visible
                    }

                    override fun onDestroy() {
                        super.onDestroy()
                        // Actions to perform when the activity is destroyed
                    }
                }
            

In the above code, we created a MainActivity class and overridden various lifecycle methods to define actions to be performed at each state.

3.3 Setting XML Layout

Now let’s modify the activity_main.xml file to define the UI.


                <?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/textView"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Hello World!"
                        android:layout_centerInParent="true" />

                </RelativeLayout>
            

In the above XML code, we used a TextView to display the text “Hello World!” at the center of the screen.

4. Navigating Between Activities

In Android apps, it is common to use multiple activities to construct the user interface. In this section, we will look at how to navigate between activities.

4.1 Creating a New Activity

We will add a new activity. Let’s create an activity named SecondActivity and set its contents as follows:


                package com.example.helloworld

                import android.os.Bundle
                import androidx.appcompat.app.AppCompatActivity

                class SecondActivity : AppCompatActivity() {
                    override fun onCreate(savedInstanceState: Bundle?) {
                        super.onCreate(savedInstanceState)
                        setContentView(R.layout.activity_second)
                    }
                }
            

4.2 Setting XML Layout

We will also modify the corresponding XML layout file activity_second.xml.


                <?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:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="This is the Second Activity"
                        android:layout_centerInParent="true" />

                </RelativeLayout>
            

4.3 Adding Code for Activity Transition

Now let’s add code to MainActivity that allows navigation to SecondActivity. We will create a button and set it to switch to the new activity when clicked.


                <Button
                    android:id="@+id/button"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Go to Second Activity"
                    android:layout_below="@id/textView"
                    android:layout_centerHorizontal="true"/>   
            

                // Add to the onCreate method of MainActivity
                val button: Button = findViewById(R.id.button)
                button.setOnClickListener {
                    val intent = Intent(this, SecondActivity::class.java)
                    startActivity(intent)
                }
            

When the button is clicked, it will transition to SecondActivity.

5. Passing Results Between Activities

Passing data between activities is also one of the important functions. Here, we will explain how to return results.

5.1 Setting Up the Activity to Return Results

First, we will modify SecondActivity to return a result.


                // SecondActivity code
                button.setOnClickListener {
                    val resultIntent = Intent()
                    resultIntent.putExtra("result", "Result from Second Activity")
                    setResult(RESULT_OK, resultIntent)
                    finish()
                }
            

5.2 Setting Up the Activity to Receive Results

Now, let’s modify MainActivity to receive results.


                // Add to MainActivity code
                val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                    if (result.resultCode == Activity.RESULT_OK) {
                        val data: Intent? = result.data
                        val resultText = data?.getStringExtra("result")
                        // Set result to TextView
                    }
                }

                button.setOnClickListener {
                    val intent = Intent(this, SecondActivity::class.java)
                    startForResult.launch(intent)
                }
            

Now MainActivity can receive results from SecondActivity and reflect it in the UI.

6. Setting Activity Flags

In Android, you can set flags in the intent when starting an activity to control its behavior.

Some of the most commonly used flags are:

  • FLAG_ACTIVITY_NEW_TASK: Starts the activity in a new task.
  • FLAG_ACTIVITY_CLEAR_TOP: Removes existing activities in the stack and starts the activity on top of them.

6.1 Example of Flags


                val intent = Intent(this, SecondActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                startActivity(intent)
            

In the above code, using FLAG_ACTIVITY_CLEAR_TOP will remove existing activities in the stack when starting SecondActivity.

7. Applying Activity Themes and Styles

You can apply various themes and styles to activities to adjust the UI. Here, we will explain how to create and apply a custom theme.

7.1 Setting the Theme

Open the res/values/styles.xml file and add a new theme.


                <style name="CustomTheme" parent="Theme.AppCompat.Light.NoActionBar">
                    <item name="colorPrimary">#FF5722</item>
                    <item name="colorPrimaryDark">#E64A19</item>
                    <item name="colorAccent">#FFC107</item>
                </style>
            

7.2 Applying the Theme

Apply the new theme to MainActivity in the AndroidManifest.xml file.


                <activity
                    android:name=".MainActivity"
                    android:theme="@style/CustomTheme">
                </activity>
            

In the above code, we set CustomTheme to be applied to the activity.

8. Ending an Activity

There are several ways to end an activity. By default, you can call the finish() method to terminate the current activity.

It is also important to note that it is automatically handled when the user presses the back button to close an activity.


                button.setOnClickListener {
                    finish()
                }
            

In the above code, clicking the button will terminate the current activity.

Conclusion

In this course, we covered how to control activities in Android apps using Kotlin. We explored various topics, including the lifecycle of an activity, creation and transition, result passing, and theme setting.

Now you have a basic understanding of activity control using Kotlin, and you are equipped with foundational knowledge necessary for developing more complex apps in the future.

I hope this course helps you on your journey in Android app development.

Kotlin Android App Development Course, Activity Lifecycle

Hello! In this article, we will take a closer look at one of the most important concepts in Android app development, the Activity Lifecycle. An Activity is a fundamental component that composes a screen where users interact, and its lifecycle defines how it changes as the app transitions between various states. As users use the app, the Activity goes through several states, and we will learn how to save or restore important information during this process.

What is an Activity?

An Activity is the most basic component that represents a screen where users can interact in Android. Activities allow for various tasks to be performed through different UI components, and multiple Activities can be combined to build an app. For example, a photo gallery app may have an Activity for selecting photos, an Activity for viewing photos, and a settings Activity.

Activity Lifecycle

The lifecycle of an Activity is managed through several callback methods such as onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(). Each method is called when the state of the Activity changes, allowing the developer to control the operation of the Activity as declared in the manifest.

1. onCreate()

This method is called when the application is first launched and typically performs UI initialization tasks. It is called only once when the Activity is created for the first time. Here, the layout is set up and data binding is usually performed.


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
    

2. onStart()

This method is called when the Activity starts to become visible to the user. It is invoked just before the Activity begins to interact with the user, meaning the Activity is on the screen but has not yet gained focus.


override fun onStart() {
    super.onStart()
    // Prepare tasks for the Activity to be shown to the user.
}
    

3. onResume()

This method is called when the user can interact with the Activity. You can write code here to optimize the UI and user interactions.


override fun onResume() {
    super.onResume()
    // This is called when the Activity gains focus and performs UI update tasks.
}
    

4. onPause()

This method is called when another Activity begins to be shown to the user. It is mainly used for saving data or releasing resources.


override fun onPause() {
    super.onPause()
    // Save necessary data before leaving the Activity.
}
    

5. onStop()

This method is called when the Activity is no longer visible. For example, it is called when another Activity completely obscures the screen or when the app moves to the background. Necessary resources can be released here if required.


override fun onStop() {
    super.onStop()
    // Stop UI updates and release resources as needed.
}
    

6. onDestroy()

This is the last method called when the Activity is terminated. Necessary tasks for memory cleanup can be performed here, usually when the Activity is no longer in use. It cleans up all resources.


override fun onDestroy() {
    super.onDestroy()
    // Perform Activity cleanup and resource release tasks.
}
    

Activity Lifecycle Sequence

The lifecycle states when an Activity is created and terminated can be represented in the following diagram.

Activity Lifecycle

Example of Utilizing Lifecycle Methods

Now, let’s demonstrate how to use Activity lifecycle methods with a practical example. Below is an example of a simple counter app that increments the count each time a button is clicked in the user interface, demonstrating how to save and restore data using lifecycle methods.


class CounterActivity : AppCompatActivity() {
    private var counter = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_counter)
        
        // Restore previous state
        savedInstanceState?.let {
            counter = it.getInt("counter", 0)
        }

        findViewById

Conclusion

In this article, we explored the Activity lifecycle in Android using Kotlin. Understanding and effectively utilizing the Activity lifecycle can greatly enhance app performance and improve user experience. In the next lesson, we will look at other Android components such as Services and Broadcast Receivers. Thank you!

course on Kotlin Android App Development, Activity ANR Issues and Coroutines

Performance is a crucial factor in Android app development. To improve user experience, the responsiveness of the application is essential. This article will explain the ANR (Application Not Responding) issue and how to solve it using Kotlin’s coroutines in detail.

1. What is the ANR (Application Not Responding) Issue?

ANR occurs when the app’s UI does not respond for more than 5 seconds while the user is using the app. In this case, the user feels as if the app has frozen, and the system automatically shows a dialog stating “The app is not responding.” The main causes of ANR are as follows:

  • Performing heavy tasks on the main (UI) thread
  • Response delays due to blocked threads
  • Synchronization issues between UI updates and data processing

1.1 Example of ANR

For instance, if a user clicks a button and a network request or a database query is executed on the main thread, ANR can occur. The following is a simple code example that can induce ANR:

class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)

            val button = findViewById

2. Introduction to Coroutines

Coroutines are lightweight threads designed to make asynchronous programming easier. By using coroutines, you can keep your code concise and readable while handling long tasks simultaneously. Coroutines can run tasks separately from the main thread, making them very useful for preventing ANR.

2.1 Advantages of Coroutines

  • Allows intuitive handling of asynchronous tasks
  • Reduces the complexity of thread management
  • Improves reusability and ease of testing

2.2 Example of Using Coroutines

Below is an example of code that uses coroutines to handle long tasks asynchronously:

import kotlinx.coroutines.*

    class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)

            val button = findViewById

3. Setting Up Coroutines

To use coroutines, you need to add the required dependencies to Gradle. Modify your build.gradle file to add the coroutine library as follows:

dependencies {
        implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
        implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'
    }

4. CoroutineScope and LifecycleScope

Coroutines need to be executed within a specific scope. In Android, you can manage coroutines using CoroutineScope and LifecycleScope. The lifecycleScope manages the lifecycle of Activities and Fragments well, allowing for safer operations during UI updates.

4.1 Example of Using CoroutineScope

You can utilize CoroutineScope for asynchronous processing, as shown below:

class MainActivity : AppCompatActivity(), CoroutineScope {
        // Set default dispatcher
        private val job = Job()
        override val coroutineContext: CoroutineContext
            get() = Dispatchers.Main + job

        override fun onDestroy() {
            super.onDestroy()
            job.cancel() // Clean up coroutines when the Activity is destroyed
        }

        // Asynchronous processing method
        private fun performAsyncTask() {
            launch {
                // Asynchronous task
                withContext(Dispatchers.IO) {
                    // Example of a long task
                    delay(2000)
                }
                // Update UI on the main thread
                Toast.makeText(this@MainActivity, "Processing Complete", Toast.LENGTH_SHORT).show()
            }
        }
    }

5. Using Coroutines to Prevent ANR

Based on what has been explained so far, you can properly utilize coroutines to solve ANR issues. Below is an example of avoiding ANR problems through a network call:

class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)

            val button = findViewById

6. Conclusion

In this article, we explored the ANR issue and the use of coroutines to solve it in depth. By utilizing coroutines, you can reduce the burden on the UI thread and provide a better experience for users. We encourage you to actively use coroutines to improve both app performance and user experience. We hope this article has been helpful for your Android app development.

7. Additional Resources

Below are links to additional resources on coroutines, ANR, and Android app development:

If you have questions or feedback, please leave a comment!

Kotlin Android app development course, displaying notifications

In Android app development, informing users or providing alerts about important events is a crucial feature. In this process, notifications can be utilized to maximize interaction with users. This course will provide a detailed introduction to creating basic notifications using Kotlin and the various modifications of notifications.

Overview of Notifications

A notification is a UI element used to convey important information when users interact with the app. Notifications consist of the following components:

  • Title: Summarizes the main message of the notification.
  • Content: Provides detailed information about the notification.
  • Icons: Icons that help visually identify the notification.
  • Action: Defines what action to take when the notification is clicked.

Preparation Steps for Implementing Notifications

Several preparatory steps are required to create notifications. The following are the steps to implement notifications.

  1. Create an Android project: Start a new project in Android Studio.
  2. Set necessary permissions: Since notifications are controlled by the system by default, you need to grant notification permissions in the app settings.

Creating Notifications with Kotlin

1. Project Setup

Create a new project in Android Studio and set up the following basic configurations.

  • Project Language: Kotlin
  • Target SDK: Android 8.0 (API 26) or higher

2. Adding Gradle Dependencies

No special libraries are required to use notification features, but it is always good to rely on the latest SDK. Add the following configuration to the build.gradle file.

dependencies {
    implementation 'com.android.support:appcompat-v7:28.0.0'
}

3. Notification Creation Code

The basic code to create a notification is as follows. This code is a simple example that shows a notification when a button is clicked.

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.core.app.NotificationCompat

class MainActivity : AppCompatActivity() {

    private lateinit var notificationManager: NotificationManager
    private val CHANNEL_ID = "example_channel"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        createNotificationChannel()

        val notifyButton: Button = findViewById(R.id.notifyButton)
        notifyButton.setOnClickListener {
            showNotification()
        }
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "Example Channel"
            val descriptionText = "Channel for example notifications"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
                description = descriptionText
            }
            notificationManager.createNotificationChannel(channel)
        }
    }

    private fun showNotification() {
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

        val builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("Hello, World!")
            .setContentText("This is a sample notification!")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)

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

4. XML Layout Configuration

You need to add the button called in the above example to the layout. The following is the content of the activity_main.xml file.

<?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">

    <Button
        android:id="@+id/notifyButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Notification"
        android:layout_centerInParent="true"/>

</RelativeLayout>

Various Notification Options

In addition to basic notifications, various options allow you to customize the style of notifications.

1. Big Text Style

Using big text style allows you to convey more information.

private fun showBigTextNotification() {
    val bigTextStyle = NotificationCompat.BigTextStyle()
        .bigText("This is a more detailed description of the notification. More text can be added here to give users detailed contextual information.")

    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle("Big Text Notification")
        .setStyle(bigTextStyle)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

    notificationManager.notify(2, builder.build())
}

2. Image Notifications

You can enhance the visual effect by adding images to the notification.

private fun showImageNotification() {
    val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image)
    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle("Image Notification")
        .setContentText("This notification contains an image!")
        .setLargeIcon(bitmap)
        .setStyle(NotificationCompat.BigPictureStyle()
            .bigPicture(bitmap))
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

    notificationManager.notify(3, builder.build())
}

Defining Actions for Notifications

You can add various actions to notifications to allow users to perform multiple tasks. The following example adds ‘Accept’ and ‘Decline’ buttons.

private fun showActionNotification() {
    val acceptIntent = Intent(this, AcceptActivity::class.java)
    val acceptPendingIntent = PendingIntent.getActivity(this, 0, acceptIntent, PendingIntent.FLAG_UPDATE_CURRENT)

    val declineIntent = Intent(this, DeclineActivity::class.java)
    val declinePendingIntent = PendingIntent.getActivity(this, 1, declineIntent, PendingIntent.FLAG_UPDATE_CURRENT)

    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle("Action Required")
        .setContentText("Please accept or decline.")
        .addAction(R.drawable.ic_accept, "Accept", acceptPendingIntent)
        .addAction(R.drawable.ic_decline, "Decline", declinePendingIntent)
        .setPriority(NotificationCompat.PRIORITY_HIGH)

    notificationManager.notify(4, builder.build())
}

Deleting and Updating Notifications

You can delete or update notifications while running. Users can update images or overwrite existing content.

private fun updateNotification() {
    val updatedBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle("Updated Notification")
        .setContentText("This notification has been updated!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

    notificationManager.notify(4, updatedBuilder.build())
}

Managing Notifications

To allow users to manage multiple notifications, you need to assign a unique ID to each notification. Using unique IDs allows you to remove or update specific notifications.

private fun removeNotification() {
    notificationManager.cancel(4)
}

Android Notification Channels

On Android O (API 26) and higher, you can use notification channels to define the nature of notifications created by the app. Depending on user settings, the visual and auditory characteristics of notifications can be modified. Through channels, users can set the priority, sound, vibration, and more for each notification.

Conclusion

If you have learned the basics of using notifications based on the content presented in this article, you can now utilize various notification types and designs to enhance user experience. Use notifications appropriately to increase the value of your app and strengthen communication with users!

References