본문 바로가기

IT/안드로이드 관련

[안드로이드] AlarmManager With Notification Example (알람매니저를 이용하여 푸쉬생성 예제)


 안녕하세요 YTS 입니다.




오늘은  알람매니저(AlarmManager)를 이용하여 푸쉬(Notification)를 생성하는 예저를 다루어볼까합니다. 추가적으로 JobScheduler를 이용하여 백그라운드에서도 반응하도록 예제를 제작하였습니다.



 우선적으로 사전지식이 필요한 JobScheduler는 안드로이드 API LEVEL 21부터 등장하였고, Android에서는 기존 무분별한 백그라운드 서비스를 제한하기위하여 JobScheduler로 대체를 하고있습니다.




저는 JobScheduler를 보다 쉽게 사용하기위해서 FireBase Jobdispatcher를 이용하였습니다. 보다 자세한 정보는 https://github.com/firebase/firebase-jobdispatcher-android  에서 확인할 수 있습니다.



1. 안드로이드 오레오대응을 위하여 Notification 채널을 애플리케이션 부분에 생성합니다.

/**
* 노티피케이션 채널 생성하기 안드로이드 버전 오레오 이상부터 필요
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = getString(R.string.notification_channel_id); // 채널 아이디
CharSequence channelName = getString(R.string.notification_channel_name); //채널 이름
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}



2. 알람을 받을 Receiver와 Notification을 생성하는부분을 구현합니다.

public class AlarmBroadcastReceiver extends BroadcastReceiver {
private final static int NOTICATION_ID = 222;

@Override
public void onReceive(Context context, Intent intent) {
Log.d("AlarmBroadcastReceiver", "onReceive");

NotificationCompat.Builder builder = new NotificationCompat.Builder(context, context.getString(R.string.notification_channel_id))
.setSmallIcon(R.drawable.ic_love_p_64px) //알람 아이콘
.setContentTitle("Title") //알람 제목
.setContentText("Text") //알람 내용
.setPriority(NotificationCompat.PRIORITY_DEFAULT); //알람 중요도

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(NOTICATION_ID, builder.build()); //알람 생성
}
}


3. Receiver를 매니페스트에 등록합니다.

<receiver
android:name=".service.AlarmBroadcastReceiver"
android:enabled="true"
android:exported="true"></receiver>





4. JobService안에 AlarmManager를 구현합니다.

public class NotificationJobFireBaseService extends JobService {

@Override
public boolean onStartJob(JobParameters job) {
Log.d("NotificationJobService", "onStartJob");
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);

Intent intent = new Intent(this, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 111, intent, PendingIntent.FLAG_UPDATE_CURRENT);
/**
* Intent 플래그
* FLAG_ONE_SHOT : 한번만 사용하고 다음에 이 PendingIntent가 불려지면 Fail을 함
* FLAG_NO_CREATE : PendingIntent를 생성하지 않음. PendingIntent가 실행중인것을 체크를 함
* FLAG_CANCEL_CURRENT : 실행중인 PendingIntent가 있다면 기존 인텐트를 취소하고 새로만듬
* FLAG_UPDATE_CURRENT : 실행중인 PendingIntent가 있다면 Extra Data만 교체함
*/

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, pendingIntent); //10초뒤 알람
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
manager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, pendingIntent);
} else {
manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, pendingIntent);
}

/**
* AlarmType
* RTC_WAKEUP : 대기모드에서도 알람이 작동함을 의미함
* RTC : 대기모드에선 알람을 작동안함
*/

return false; // Answers the question: "Is there still work going on?"
}

@Override
public boolean onStopJob(JobParameters job) {
return false; // Answers the question: "Should this job be retried?"
}
}


5. JobService를 Android Manifests에 등록합니다.

<service
android:name=".service.NotificationJobFireBaseService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE" />
</intent-filter>
</service>


6.  Job을 스케쥴러에 등록합니다.

public class JobSchedulerStart {
private static final int JOB_ID = 1111;

public static void start(Context context) {

FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job myJob = dispatcher.newJobBuilder()
.setService(NotificationJobFireBaseService.class) // 잡서비스 등록
.setTag("TSLetterNotification") // 태그 등록
.setRecurring(true) //재활용
.setLifetime(Lifetime.FOREVER) //다시켜도 작동을 시킬껀지?
.setTrigger(Trigger.executionWindow(0, 60)) //트리거 시간
.setReplaceCurrent(true)
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
.build();
dispatcher.mustSchedule(myJob);
}
}



7.  실행시킵니다.


public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JobSchedulerStart.start(this);
}
}



 여기까지 따라오셨다면 정말 쉽게 백그라운드서비스와 알람 그리고 푸쉬를 이용하는 예제를 완성시키셨을겁니다! 순서대로 쭉 따라하시면 금방 구현이 될거예요!


여기서 끝이면 서운하겠죠? 좀더 이글을 읽는분들을 위해 예제소스를 GIT에 올려놓았습니다.


https://github.com/YunTaeSik/AlarmManagerExample/tree/master


이글을 보시고 보다 쉽게 구현하시길 바랍니다 : )


궁금한점은 댓글로 남겨주세요!