본문 바로가기
Language/Android

[Android] 안드로이드_알림(바) 구현하기 5 - 클릭 시 Activity로 넘어가기 (feat. PendingIntent)

by 썸머워즈 2019. 11. 24.
반응형


PendingIntent를 이용한 Notification 클릭 시 반응하기


Notification 알림을 클릭 시 해당 정보를 화면에 보여주거나 하기 위해


이동할 필요성을 느껴 찾아보고 직접 적용한 결과를 기록해두고자 한다.


Notification에서 클릭 시 Acitivity로 이동하기 위해


여타 Acitivity 이동때 Intent를 쓰는거와 마찬가지로


Pendingintent 라는것을 사용해야한다.

PendingIntent mPendingIntent = PendingIntent.getActivity( 
MainActivity.this,
0, // 보통 default값 0을 삽입
new Intent(getApplicationContext(),CustomNotiActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT
);

new Intent 안에 들어갈 Activity는 기존과 마찬가지로 이동할 Class를 적어주면 된다.


숫자 '0' 이 들어가는 부분은 requestCode 부분인데 보통 default값으로 0을 넣어주곤 한다.


아래에 FLAG_UPDATE_CURRENT 도 보통 기본으로 사용하는 옵션이다.

해당 위치에 들어가는 옵션들을 살펴보면


- FLAG_CANCEL_CURRENT : 이전에 생성한 PendingIntent는 취소하고 새로 만든다.

- FLAG_IMMUTABLE : 생성된 PendingIntent 는 수정 불가능하도록 한다.

- FLAG_NO_CREATE : 생성된 PendingIntent 를 반환한다, 이미 생성된 PendingIntent가 없다면 null을 retrun 한다.

- FLAG_ONE_SHOT : 해당 flag로 생성한 PendingIntent 는 일회성이다.

- FLAG_UPDATE_CURRENT : 이미 생성된 PendingIntent가 존재하면 해당 Itent의 Extra DATA만 변경한다.


PendingIntent 를 통해 값도 같이 보내주려면 기존 Intent에서 사용하는 방식 그대로 사용하면 된다.

PendingIntent mPendingIntent = PendingIntent.getActivity(
MainActivity.this,
0, // 보통 default값 0을 삽입
new Intent(getApplicationContext(),CustomNotiActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT
);

NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this,NOTIFICATION_ID)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_sync_noti))
.setContentTitle("제목")
.setContentText("상세내용")
.setSmallIcon (R.drawable.ic_sync_noti_small)
.setContentIntent(mPendingIntent) // 상세보기를 누르지 않더라도 mPendingIntent 효과 발동
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setOngoing(true) // 사용자가 직접 못지우게 계속 실행하기.
;

notificationManager.notify(0, builder.build());

이제 NotificationCompat.Builder 에서


setContentIntent() 를 사용해서 위에서 선언한 PendingIntent를 넣어주기만하면


해당 Notification실행 시 클릭할 경우 해당 Activity로 넘어갈 수 있다.


반응형


댓글

TOP