투케이2K

649. (Android/Java) [Android 13] WorkManager 워커 매니저 사용해 백그라운드 서비스 동작 수행 - Worker 본문

Android

649. (Android/Java) [Android 13] WorkManager 워커 매니저 사용해 백그라운드 서비스 동작 수행 - Worker

투케이2K 2023. 9. 11. 20:04

[개발 환경 설정]

개발 툴 : AndroidStudio

 

[소스 코드]

// -----------------------------------------------------------
[1] : build.gradle 파일에서 의존성 부여 수행
// -----------------------------------------------------------

    // [Android WorkManager 의존성 부여]

    def work_version = "2.8.0" // [CompileSdk / targetSdk : 33]
    //def work_version = "2.7.0" // [CompileSdk / targetSdk : 31]

    // (Java only)
    implementation "androidx.work:work-runtime:$work_version"

    // Kotlin + coroutines
    implementation "androidx.work:work-runtime-ktx:$work_version"

    // optional - GCMNetworkManager support
    implementation "androidx.work:work-gcm:$work_version"

    // optional - Test helpers
    androidTestImplementation "androidx.work:work-testing:$work_version"

    // optional - Multiprocess support
    implementation "androidx.work:work-multiprocess:$work_version"









// -----------------------------------------------------------
[2] : 백그라운드 서비스 동작 Worker 클래스 생성 실시
// -----------------------------------------------------------

package com.example.javaproject;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

public class WorkManagerService extends Worker {


    /**
     * // --------------------------------------------------------------------------------------
     * TODO [클래스 설명]
     * // --------------------------------------------------------------------------------------
     * 1. WorkManager 작업 관리 클래스
     * // --------------------------------------------------------------------------------------
     * */





    // -----------------------------------------------------------------------------------------
    // TODO [클래스 생성자 초기화]
    // -----------------------------------------------------------------------------------------
    public WorkManagerService(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }





    // -----------------------------------------------------------------------------------------
    // TODO [doWork] : 작업 수행 및 결과 값 반환
    // -----------------------------------------------------------------------------------------
    @NonNull
    @Override
    public Result doWork() {
        S_Log._W_("서비스 작업 동작 수행", null);

        // -----------------------------------------
        // [1]. 인풋으로 전달 받은 데이터 가져온다
        // -----------------------------------------
        Data inputData = getInputData();

        int number = inputData.getInt("number", 0);


        // -----------------------------------------
        // [2]. 조건 체크 수행
        // -----------------------------------------
        if (number > 0){ // [0 보다 큰 경우]

            // -----------------------------------------
            // [3]. for 문을 수행하면서 카운트 다운 수행
            // -----------------------------------------
            for (int i = number; i >= 0; i--){
                S_Log._D_("작업 진행 중", new String[]{ String.valueOf(i) });

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    return Result.failure(); // [실패 반환]
                }

            }

        }
        else { // [0 보다 작거나 같은 경우]

            return Result.failure(); // [실패 반환]

        }

        // -----------------------------------------
        // [4]. 최종 작업을 완료한 경우 데이터 반환
        // -----------------------------------------
        Data outPutData = new Data.Builder()
                .putInt("number", number)
                .build();

        return Result.success(outPutData);

    }


} // TODO [클래스 종료]








// -----------------------------------------------------------
[3] : 메인 화면에서 백그라운드 서비스 동작 호출
// -----------------------------------------------------------

        try {

            // [Data 선언 : 인풋 값 데이터]
            Data data = new Data.Builder()
                    .putInt("number", 3)
                    .build();


            // [Constraints 선언 : WorkManger 실행 조건 지정]
            Constraints constraints = new Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED) // [네트워크 연결 된 상태]
                    .build();


            // [OneTimeWorkRequest : 일회성 작업 수행] / [PeriodicWorkRequest : 주기적 작업 수행]
            OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(WorkManagerService.class)
                    .setInputData(data) // 초기 삽입 데이터
                    .setConstraints(constraints) // 실행 조건 지정
                    .setInitialDelay(5, TimeUnit.SECONDS) // [딜레이 시간 지정]
                    .addTag("workRequest")
                    .build();


            // [WorkManager 인스턴스 생성 및 enqueue 에 작업 담기 >> 수행]
            WorkManager workManager = WorkManager.getInstance(this);
            workManager.enqueue(workRequest); // 작업 큐에 담고 >> 실행


            // [getWorkInfosByTagLiveData : Worker의 상태 확인]
            workManager.getWorkInfoByIdLiveData(workRequest.getId())
                    .observe(this, workStatus -> {

                        if (workStatus.getState() == WorkInfo.State.SUCCEEDED) { // [응답 성공]
                            S_Log._W_("onChanged Work Status [SUCCEEDED]", new String[]{ workStatus.getState().toString() });
                        }
                        else if (workStatus.getState() == WorkInfo.State.FAILED){ // [응답 에러]
                            S_Log._E_("onChanged Work Status [FAILED]", new String[]{ workStatus.getState().toString() });
                        }
                        else if (workStatus.getState() == WorkInfo.State.ENQUEUED){ // [작업 큐에 담김]
                            S_Log._D_("onChanged Work Status [ENQUEUED]", new String[]{ workStatus.getState().toString() });
                        }

                    });

        }
        catch (Exception e){
            e.printStackTrace();
        }
 

[결과 출력]

 

D///===========//: ================================================
I/: [LOG :: CLASS PLACE :: com.example.javaproject.A_Intro.lambda$onCreate$0(A_Intro.java:304)]
I/: ----------------------------------------------------
I/: [LOG :: NOW TIME :: 2023-09-11 16:54:41 월요일]
I/: ----------------------------------------------------
I/: [LOG :: DESCRIPTION :: onChanged Work Status [ENQUEUED]]
I/: ----------------------------------------------------
I/: [LOG :: ENQUEUED]
D///===========//: ================================================


W///===========//: ================================================
I/: [LOG :: CLASS PLACE :: com.example.javaproject.WorkManagerService.doWork(WorkManagerService.java:42)]
I/: ----------------------------------------------------
I/: [LOG :: NOW TIME :: 2023-09-11 16:54:46 월요일]
I/: ----------------------------------------------------
I/: [LOG :: DESCRIPTION :: 서비스 작업 동작 수행]
W///===========//: ================================================


D///===========//: ================================================
I/: [LOG :: CLASS PLACE :: com.example.javaproject.WorkManagerService.doWork(WorkManagerService.java:61)]
I/: ----------------------------------------------------
I/: [LOG :: NOW TIME :: 2023-09-11 16:54:46 월요일]
I/: ----------------------------------------------------
I/: [LOG :: DESCRIPTION :: 작업 진행 중]
I/: ----------------------------------------------------
I/: [LOG :: 3]
D///===========//: ================================================


D///===========//: ================================================
I/: [LOG :: CLASS PLACE :: com.example.javaproject.WorkManagerService.doWork(WorkManagerService.java:61)]
I/: ----------------------------------------------------
I/: [LOG :: NOW TIME :: 2023-09-11 16:54:47 월요일]
I/: ----------------------------------------------------
I/: [LOG :: DESCRIPTION :: 작업 진행 중]
I/: ----------------------------------------------------
I/: [LOG :: 2]
D///===========//: ================================================


D///===========//: ================================================
I/: [LOG :: CLASS PLACE :: com.example.javaproject.WorkManagerService.doWork(WorkManagerService.java:61)]
I/: ----------------------------------------------------
I/: [LOG :: NOW TIME :: 2023-09-11 16:54:48 월요일]
I/: ----------------------------------------------------
I/: [LOG :: DESCRIPTION :: 작업 진행 중]
I/: ----------------------------------------------------
I/: [LOG :: 1]
D///===========//: ================================================


D///===========//: ================================================
I/: [LOG :: CLASS PLACE :: com.example.javaproject.WorkManagerService.doWork(WorkManagerService.java:61)]
I/: ----------------------------------------------------
I/: [LOG :: NOW TIME :: 2023-09-11 16:54:49 월요일]
I/: ----------------------------------------------------
I/: [LOG :: DESCRIPTION :: 작업 진행 중]
I/: ----------------------------------------------------
I/: [LOG :: 0]
D///===========//: ================================================


W///===========//: ================================================
I/: [LOG :: CLASS PLACE :: com.example.javaproject.A_Intro.lambda$onCreate$0(A_Intro.java:298)]
I/: ----------------------------------------------------
I/: [LOG :: NOW TIME :: 2023-09-11 16:54:50 월요일]
I/: ----------------------------------------------------
I/: [LOG :: DESCRIPTION :: onChanged Work Status [SUCCEEDED]]
I/: ----------------------------------------------------
I/: [LOG :: SUCCEEDED]
W///===========//: ================================================


 

반응형
Comments