Monday, September 2, 2019

android kotlin - Notification progress bar example

MainActivity.kt

package com.example.jetpack

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

        // Create and register notification channel api 26+
        val channelId = "My_Channel_ID"
        val notificationId = 1
        createNotificationChannel(channelId)

        btn.setOnClickListener{
            val builder = NotificationCompat.Builder(this,channelId)
                .setContentTitle("Download Task")
                .setContentText("Downloading your file...")
                .setSmallIcon(R.drawable.ic_action_info)

            val max = 100
            var progress = 0
            val handler = Handler()

            with(NotificationManagerCompat.from(this)){
                builder.setProgress(max,progress,true)
                notify(notificationId,builder.build())

                Thread(Runnable{
                    while (progress < 100){
                        progress +=1

                        try {
                            Thread.sleep(100)
                        }catch (e:InterruptedException){
                            e.printStackTrace()
                        }

                        handler.post(Runnable {
                            if (progress == 100){
                                builder.setContentText("Download complete.")
                                builder.setProgress(0,0,false)
                            }else{
                                builder.setContentText("complete $progress of $max")
                                builder.setProgress(max,progress,true)
                            }

                            notify(notificationId,builder.build())
                        })
                    }
                }).start()
            }
        }
    }


    private fun createNotificationChannel(channelId:String) {
        // Create the NotificationChannel, but only on API 26+ (Android 8.0) because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            val name = "My Channel"
            val channelDescription = "Channel Description"
            val importance = NotificationManager.IMPORTANCE_DEFAULT

            val channel = NotificationChannel(channelId,name,importance)
            channel.apply {
                description = channelDescription
            }

            // Finally register the channel with system
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="Show Notification"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
</androidx.constraintlayout.widget.ConstraintLayout>
More android examples