반응형

Notification

설명

  • 알림창 영역에 알림 메시지 기능을 제공
  • 메시지를 터치하여 애플리케이션을 실행할 수 있도록 유도할 수 있다.
  • Notification Channel을 이용하면 채널이라는 그룹으로 묶어 채널 별로 설정을 따로 관리할 수 있다. (안드로이드 8.0 Oreo 버전 이상부터 지원)

코드

res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="click" />

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

        val button = findViewById<Button>(R.id.button)

        button.setOnClickListener {
            val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)

            val builder = getNotificationBuilder("channel1", "첫 번째 채널")
            builder.setTicker("Ticker")
            builder.setSmallIcon(android.R.drawable.ic_menu_search)
            builder.setLargeIcon(bitmap)
            builder.setNumber(100)
            builder.setAutoCancel(true) // 메시지 터치시 앱 실행 후 메시지 자동 제거
            builder.setContentTitle("Content Title")
            builder.setContentText("Content Text")

            val notification = builder.build()

            val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            manager.notify(10, notification) // id값이 동일하면 동일 메시지로 판단
        }
    }

    private fun getNotificationBuilder(id: String, name: String): NotificationCompat.Builder {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val channel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT) // IMPORTANCE값에 따라 보여지는 순서가 달라진다
            channel.enableLights(true) // 알람 조명 밝힐 것인지에 대한 설정
            channel.lightColor = Color.RED // 알람 조명 색 설정
            channel.enableVibration(true) // 진동 설정
            manager.createNotificationChannel(channel)

            NotificationCompat.Builder(this, id)
        } else {
            NotificationCompat.Builder(this)
        }
    }
}

참고

반응형

'Development > Android' 카테고리의 다른 글

[Android] File IO  (0) 2021.02.09
[Android] Permission  (0) 2021.02.09
[Android] Application  (0) 2021.02.09
[Android] ViewModel  (0) 2021.02.09
[Android] LiveData  (0) 2021.02.09

+ Recent posts