Android

[안드로이드/메시징] Pending Intent

gangmini 2023. 4. 13. 23:55
반응형

Pending Intent

  • Notification 메시지를 통해 애플리케이션의 Activity를 실행할 때 사용 (알림 누르면 해당 앱으로 가는 것 구현)
  • Pending Intent를 통해 실행되는 Activity로 데이터 전달도 가능
// 기본 리스트 다이얼로그 (다이얼로그에 리트스뷰를 넣어 커스텀 한다고 생각하면 됨)
binding.button.setOnClickListener {
    //var builder = NotificationCompat.Builder(this) -> 8.0 이상은 채널 매개변수가 하나 더 있음
    val builder = getNotificationBuilder("pending", "pending intent")

    builder.setContentTitle("nontification1_pending intent")
    builder.setContentText("알림 메시지 1 입니다.")

    // 메세지 아이콘
    builder.setSmallIcon(android.R.drawable.ic_menu_search)
    val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
    builder.setLargeIcon(bitmap)
    // 메세지를 터치하면 자동으로 제거됨
    builder.setAutoCancel(true)
            
    val intent1 = Intent(this, SecondActivity::class.java) // 실행할 액티비티 인텐트 객체
    intent1.putExtra("data1",100)
    intent1.putExtra("data2","data2")

    // 메시지를 터치하면 실행할 Activity를 관리하는 intent를 생성
    val pending1 = PendingIntent.getActivity(this, 10, intent1, PendingIntent.FLAG_MUTABLE) // activity를 띄울 때 화면을 갱신해서 띄움
    // requestCode로 새로 실행하는 액티비티에서 번호 확인 가능
    builder.setContentIntent(pending1)

    // 메세지 객체를 설정
    val notification = builder.build()
    // 알림 메시지를 관리하는 객체를 추출
    val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    // 알림 메시지 출력
    manager.notify(10, notification) // id : 메세지를 표시하는 자리, 이 id가 같으면 이 자리에 계속 덮어씌워져서 메시지가 나타남 (채널 id와는 다르다!)

}

[SecondActivity.kt]

  • 데이터 전달도 Intent 데이터 전달 방식과 동일
// Activity를 실행했을 때 사용한 Intent를 통해 데이터 추출
val data1 = intent.getIntExtra("data1",0)
val data2 = intent.getStringExtra("data2")

second_binding.textView2.text = "${data1}\n"
second_binding.textView2.append("${data2}")

 

Action

  • 알림 메세지에 Button 같은걸 배치에 지정된 Activity를 실행할 수 있도록 설정
  • 안드 4.0 까지는 메세지당 하나의 액티비티만 실행 가능 -> 4.1 이후 하나의 메세지에서 여러 액티비티 선택적으로 실행 가능 (메세지를 눌렀을 때 실행될 액티비티, 버튼(Action)을 눌렀을 때 실행될 액티비티 각각 설정 가능)
// Action 설정
val intent2 = Intent(this, ThridActivity::class.java) // 다른 액티비티 정보를 담은 인텐트
val pending2 = PendingIntent.getActivity(this, 100, intent2, PendingIntent.FLAG_MUTABLE) // 다른 액티비티로 이동하기 위한 인텐트
val builder2 = NotificationCompat.Action.Builder(android.R.drawable.ic_menu_search, "Action1", pending2) // 액션에 대한 빌더 객체 생성
val action2 = builder2.build() // 액션에 대한 빌더를 빌드
builder.addAction(action2)  // 기본 메세지 객체 빌더에 액션 빌더를 추가 (액션용 버튼을 추가한다고 생각)

기존 코드에 위 코드를 추가해서 메세지에 Action 버튼 같은걸 만들고 그걸 클릭하면 지정한 액티비티로 이동할 수 있도록 할 수 있다.

 

* 뭐가 하도 많아서 헷갈린다.....

Intent 객체 -> 새로 실행할 액티비티의 정보를 담음

Pending Intent 객체 -> '메시징' 에서 다른 액티비티로 이동하기 위한 인텐트 객체

builder 객체 -> 메시징 관련 객체들을 빌드하는 것을 돕는 객체 

반응형