알림(Notification)에서 활동을 시작할 때 사용자가 예상하는 탐색 환경을 유지해야 한다. 뒤로 탭하면 앱의 정상적인 작업 흐름을 통해 홈 화면으로 돌아가고, 최근 작업 화면을 열면 활동이 별도의 작업으로 표시되어야 한다. 탐색 환경을 유지하려면 새로운 작업에서 활동을 시작해야 한다.
PendingIntent에서는 새로운 작업 및 백 스택을 만들기 위해 알림 작업에 PendingIntent를 설정하는 방법에 관해 설명한다. 정확한 설정 방법은 시작하는 활동의 유형에 따라 다르다.
간략하게 말하자면 사용자가 Notification을 이용하여 다른 intent로 넘어가기 위한 설정이다.
Type
- PendingIntent.getActivity(Context context, int requestCode, Intent intent, int flags);
- PendingIntent.getService(Context context, int requestCode, Intent intent, int flags);
- PendingIntent.getBroadcast(Context context, int requestCode, Intent intent, int flags);
Flags
- FLAG_UPDATE_CURRENT: pendingintent가 이미 존재할 경우, Extra Data를 대체한다
- FLAG_CANCEL_CURRENT: pendinIntent가 이미 존재할 경우, 기존 pendinIntent를 취소하고 새롭게 생성한다
- FLAG_IMMUTABLE: 기존 pendingintent는 변경되지 않고, 새로 데이터를 추가한 pendingintent를 보내도 무시한다
- FLAG_NO_CREATE: 기존에 pendingIntent가 존재하지 않으면 Null값을 리턴한다
- FLAG_ONE_SHOT: 단 한 번만 사용할 수 있는 pendingIntent이다
Ex
// MainActivity.java
package com.***.extendproject;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button notiBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notiBtn = findViewById(R.id.noti_example);
notiBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_ID = "101";
String NOTIFICATION_CHANNEL = "channelId";
// pending intent 생성
Intent notiIntnet = new Intent(getApplicationContext(), NotiActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notiIntnet, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent);
notificationManager.notify(11, builder.build());
}
});
}
}