본문 바로가기
Android

[깡쌤의 안드로이드 프로그래밍 with 자바 - 2022 - 쌤즈] 정리 16 - Notification, Person, Message, RemoteInput

by 들풀민들레 2022. 5. 9.

책의 모든 내용을 저자 직강으로 진행한 강의는 ssamz.com 에서 들으실 수 있습니다.

 

 

본 글은 [깡쌤의 안드로이드 프로그래밍 with 자바 - 2022 - 쌤즈] 의 내용을 발췌한 것입니다.
좀더 자세한 내용은 책 혹은 인강(www.ssamz.com)을 통해 확인해 주세요.

 

메시지 스타일 : Message Style
메시지 스타일 알림은 여러 사람이 주고받은 메시지를 구분해서 출력할 때 사용합니다. Message
객체로 생성되며, 3가지 정보를 보여줍니다.

  • Message(CharSequence text, long timestamp, Person person)


첫 번째 매개변수는 메시지 내용이며, 두 번째 매개변수는 메시지가 발생한 시각입니다. 메시지 스타일
알림은 어떤 사람이 보냈는지에 대한 정보가 필요합니다. 이를 세 번째 매개변수인 Person 객체로
설정합니다. Person은 메시지 스타일 알림에 출력될 한 사람의 정보를 담는 클래스입니다.

 

Person sender1 = new Person.Builder()
.setName("kkang")
.setIcon(IconCompat.createWithResource(this, R.drawable.person1))
.build();
Person sender2 = new Person.Builder()
.setName("kim")
.setIcon(IconCompat.createWithResource(this, R.drawable.person2))
.build();

위의 코드에서는 두 명에 대한 정보를 함께 표현하고자 Person 객체를 두 개 생성했습니다. 각 Person
객체에 이름, 아이콘 등을 설정할 수 있습니다.


이제 이 Person 객체를 MessageStyle을 이용해 알림에 출력할 수 있습니다.

 

NotificationCompat.MessagingStyle.Message message = new NotificationCompat.MessagingStyle.
Message("hello", System.currentTimeMillis(), sender2);
NotificationCompat.MessagingStyle style = new NotificationCompat.MessagingStyle(sender1)
.addMessage("world", System.currentTimeMillis(), sender1)
.addMessage(message);
builder.setStyle(style);

 

위처럼 작성하면 아래 그림처럼 각 Person의 정보가 메시지 스타일로 보입니다.

 

 

원격입력 : RemoteInput


원격입력이란 알림에 글을 직접 입력할 수 있도록 하는 기능입니다.

 

 

위의 그림은 메시지 앱의 알림입니다. 사용자가 답장을 할 때 메시지 앱을 실행시켜서 할 수 있습니다.
그런데 알림에서 바로 글을 입력할 수 있다면 편리할 것입니다. 이를 지원하는 것이 액션의 일종인
원격입력입니다. 위의 화면에서 답장을 누르면 아래와 같이 사용자에게 글을 입력받는 공간이 생깁니다.

 

원격 입력을 구현하기 위해서는 RemoteInput을 이용합니다. RemoteInput에 사용자에게 입력받을
정보를 설정한 후에 액션에 추가하는 구조입니다.

 

String replyKey = "message";
String replyLabel = "답장";
RemoteInput.Builder remoteBuilder = new RemoteInput.Builder(replyKey);
remoteBuilder.setLabel(replyLabel);
RemoteInput remoteInput = remoteBuilder.build();

위와 같이 RemoteInput.Builder에 정보를 설정한 후, RemoteInput 객체를 생성합니다. 이때
버전호환성을 위해 androidx.core.app.RemoteInput을 이용합니다.


RemoteInput.Builder 생성자의 매개변수는 사용자 입력을 식별하는 값입니다. 이 식별자 값은
임의의 문자열로 지정할 수 있습니다. setLabel () 함수로 설정하는 값은 입력 화면에 출력되는 힌트
문자열입니다.


RemoteInput도 액션의 일종이므로 터치 이벤트를 처리하는 PendingIntent가 준비되어야
합니다. 이때 사용하는 PendingIntent 생성자의 세 번째 매개변수 값은 FLAG_MUTABLE 상수로
지정합니다,

 

Intent remoteIntent = new Intent(this, MyReceiver.class);
PendingIntent remotePendingIntent = PendingIntent.getBroadcast(this, 20, remoteIntent,
PendingIntent.FLAG_MUTABLE);

PendingIntent로 액티비티, 서비스, 브로드캐스트 리시버 등을 실행할 수 있습니다. 그런데 대부분
사용자 입력을 화면 전환 없이 처리할 때 원격입력을 사용하므로, 브로드캐스트 리시버에 많이
적용됩니다. 브로드캐스트 리시버에 대해서는 이후에 자세히 알아보도록 하겠습니다.


이제 액션에 RemoteInput을 적용하면 됩니다.

 

NotificationCompat.Action.Builder remoteActionBuilder = new NotificationCompat.Action.Builder(
android.R.drawable.stat_notify_chat,
"답장",
remotePendingIntent
);
remoteActionBuilder.addRemoteInput(remoteInput);
NotificationCompat.Action remoteAction = remoteActionBuilder.build();
builder.addAction(remoteAction);

RemoteInput에 의해 아래의 코드로 입력된 문자열을 획득할 수 있습니다. 아래 코드는 브로드캐스트
리시버가 실행되었다는 가정하에 작성되었습니다.

 

public class MyReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		String replyTxt =
			RemoteInput.getResultsFromIntent(intent).getCharSequence("message").toString();
		Log.d("kkang","receiver...."+replyTxt);
		NotificationManager manager
			= (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		manager.cancel(222);
	}
}

getCharSequence ( ) 함수의 매개변수는 RemoteInput을 등록할 때 지정했었던 식별자
문자열입니다. 문자열을 획득한 후에는 NotificationManager로 cancel () 혹은 notify () 함수를
호출해 신호를 잘 받았다고 알려줘야 합니다. 이때 cancel () 함수의 매개변수는 알림의 식별자로,
RemoteInput을 이용한 곳에서 알림을 띄울 때 사용했던 식별자와 같아야 합니다

 

책의 모든 내용을 저자 직강으로 진행한 강의는 ssamz.com 에서 들으실 수 있습니다.