공부용 블로그

1. Job Scheduler - Implement a JobService 본문

Android

1. Job Scheduler - Implement a JobService

tomato212 2020. 8. 11. 20:14

이번에는 알림 스케줄러라는 앱을 만듭니다. 앱은 사용자가 제약 조건을 선택하고 작업을 예약 할 수 있도록하여 JobScheduler 프레임워크를 보여줍니다. 해당 작업이 실행되면 앱에서 알림을 게시합니다. (이 앱에서 알림은 사실상 "job"입니다.)

Task 1: Implement a JobService

먼저 조건에 따라 결정된 시간에 실행될 서비스를 만듭니다. 시스템은 자동으로 JobService를 실행합니다. 구현해야하는 유일한 부분은 onStartJob () 콜백과 onStopJob () 콜백입니다.

 

onStartJob()

- 시스템이 작업을 실행해야 한다고 결정할 때 호출됩니다. 이 메서드에서는 수행할 작업을 구현합니다.

- 작업이 별도의 스레드에서 계속되어야하는지 여부를 나타내는 boolean을 리턴합니다. true이면 작업이 다른 스레드로 오프로드되고 앱은 해당 스레드에서 명시적으로 jobFinished ()를 호출하여 작업이 완료되었음을 나타내야합니다. false 인 경우 시스템은 onStartJob()이 끝날 때까지 작업이 완료되었음을 인식하고 사용자를 대신하여 jobFinished()를 호출합니다.

 

Note: The onStartJob() method is executed on the main thread, and therefore any long-running tasks must be offloaded to a different thread. In this app, you are simply posting a notification, which can be done safely on the main thread.

 

onStopJob()

- JobInfo에 설명된 조건이 더 이상 충족되지 않으면 작업을 중지해야하며 시스템은 onStopJob()을 호출합니다. 

- onStopJob () 콜백은 작업이 완료되지 않은 경우 수행할 작업을 결정하는 boolean을 반환합니다. 반환값이 true이면 작업이 다시 예약됩니다. 그렇지 않으면 작업이 삭제됩니다.

=> 작업이 완료되지 않은 것 = JonInfo의 조건 불충족 ?? 일단 코드를 모두 작성한 후 앱을 실행해보고 다시 이해해보기로.

1.1 Create the project and the NotificationJobService class

사용중인 최소 SDK가 API 21인지 확인합니다. API 21 이전에는 JobScheduler가 일부 필수 API가 누락되어 작동하지 않습니다.

  1. Create a new Java project called "Notification Scheduler". Use API 21 as the target SDK, and use the Empty Activity template.
  2. Inside the com.android.example.notificationscheduler package, create a new Java class that extends JobService. Call the new class NotificationJobService.
  3. Add the required methods, which are onStartJob() and onStopJob(). Click the red light bulb next to the class declaration and select Implement methods, then select OK.
  4. In your AndroidManfest.xml file, inside the <application> tag, register your JobService with the following permission : 
<service
   android:name=".NotificationJobService"
   android:permission="android.permission.BIND_JOB_SERVICE"/>

1.2 Implement onStartJob()

Implement the following steps in NotificationJobService.java:

  1. Add an image asset to use as a notification icon 
     for the "Job" notification. Name the image ic_job_running.
  2. Declare a member variable for the notification manager and a constant for the notification channel ID.
NotificationManager mNotifyManager;

// Notification channel ID.
private static final String PRIMARY_CHANNEL_ID =
       "primary_notification_channel";

3. Inside the onStartJob() method, define a method to create a notification channel.

/**
* Creates a Notification channel, for OREO and higher.
*/
public void createNotificationChannel() {

   // Define notification manager object.
   mNotifyManager =
           (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

   // Notification channels are only available in OREO and higher.
   // So, add a check on SDK version.
   if (android.os.Build.VERSION.SDK_INT >=
           android.os.Build.VERSION_CODES.O) {

       // Create the NotificationChannel with all the parameters.
       NotificationChannel notificationChannel = new NotificationChannel
               (PRIMARY_CHANNEL_ID,
                       "Job Service notification",
                       NotificationManager.IMPORTANCE_HIGH);

       notificationChannel.enableLights(true);
       notificationChannel.setLightColor(Color.RED);
       notificationChannel.enableVibration(true);
       notificationChannel.setDescription
               ("Notifications from Job Service");

       mNotifyManager.createNotificationChannel(notificationChannel);
   }
} 

4. onStartJob() 내에서 메서드를 호출하여 알림채널을 만듭니다. 앱의 MainActivity를 시작하는 PendingIntent를 만듭니다. 이 인텐트는 알림의 Content Intent 입니다.

//Create the notification channel
createNotificationChannel();

//Set up the notification content intent to launch the app when clicked
PendingIntent contentPendingIntent = PendingIntent.getActivity
       (this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

5. onStartJob ()에서 다음 속성을 사용하여 알림을 구성하고 전달합니다.

 

6. 문자열을 추출하십시오.

7. 이 앱의 경우 모든 작업이 onStartJob() 콜백에서 완료되므로(Note:...In this app, you are simply posting a notification, which can be done safely on the main thread.) onStartJob()이 false를 반환하는지 확인합니다.

 

=> false이면 메인스레드에서 작업이 끝날때까지 기다리고, true이면 다른 스레드로 오프로드.

 

Here is the complete code for the onStartJob() method:

@Override
public boolean onStartJob(JobParameters jobParameters) {

   //Create the notification channel
   createNotificationChannel();

   //Set up the notification content intent to launch the app when clicked
   PendingIntent contentPendingIntent = PendingIntent.getActivity
           (this, 0, new Intent(this, MainActivity.class),
                   PendingIntent.FLAG_UPDATE_CURRENT);

   NotificationCompat.Builder builder = new NotificationCompat.Builder
           (this, PRIMARY_CHANNEL_ID)
           .setContentTitle("Job Service")
           .setContentText("Your Job ran to completion!")
           .setContentIntent(contentPendingIntent)
           .setSmallIcon(R.drawable.ic_job_running)
           .setPriority(NotificationCompat.PRIORITY_HIGH)
           .setDefaults(NotificationCompat.DEFAULT_ALL)
           .setAutoCancel(true);

   mNotifyManager.notify(0, builder.build());
   return false;
}

 

8. Make sure that onStopJob() returns true, because if the job fails, you want the job to be rescheduled instead of dropped.

 

순서를 다시 요약해보자면 아래와 같다.

 

1. JobService 를 상속받는 NotificationJobService 자바 클래스 생성

2. 매니페스트에 서비스 등록 및 관련 퍼미션 허용

3. NotificationJobService 클래스의 멤버 변수로 노티피케이션 매니저와 노티피케이션 채널 아이디 선언

4. 노티 채널 생성할 메서드 구현

5. onStartJob() 에서 노티 채널 호출

6. onStartJob() 에서 MainActivity를 시작하는 펜딩 인텐트 생성.

7. 노티피케이션 알림을 속성에 맞게 구성하고 전달

8. onStartJob()이 false를 반환하는지 확인

 - true : 작업이 다른 스레드로 오프로드되고 앱은 해당 스레드에서 명시적으로 jobFinished ()를 호출하여 작업이 완료되었음을 나타냄

 - false : 시스템은 onStartJob ()이 끝날 때까지 작업이 완료되었음을 인식하고 사용자를 대신하여 jobFinished()를 호출

9. onStopJob()이 true를 반환하는지 확인

 - JobInfo에 설명된 조건이 더 이상 충족되지 않으면 작업을 중지해야 하며 시스템은 onStopJob()을 호출

 - onStopJob() 콜백은 작업이 완료되지 않은 경우 수행할 작업을 결정하는 boolean을 반환.

 - true : 작업 재예약

 - false : 작업 삭제

 

다음 시간에 이어서 JobService를 구현해보자