📱Mobile/React Native

[React Native] 앱 종료 시에도 React Native 코드 실행

뉴발자 2023. 12. 18.
728x90

 

 

 

 

 

 

 

 

 

 

 

 

 

 

그림 1-1. React Native

 

 

개요

안드로이드 앱을 개발하던 중 도즈모드에 대해 알게됐다.

 

도즈모드 테스트를 위해 일정 시간마다 서버 API와 통신하는 코드를 작성했다.

 

하지만 앱이 백그라운드 상태가 되면 코드가 동작하지 않았다.

 

 

사용 라이브러리

우선 원하는 앱 동작 방식을 정리했다.

 

 

1. 앱을 켠 후 로그인을 한다.

 

2. 로그인된 상태에서 앱을 종료시킨다.

 

3. 앱이 종료되어도 일정 시간(30분) 마다 서버 API와 통신한다.

 

4. 통신 결과로 앱이 도즈모드 상태에 들어가는지 확인한다.

 

 

위 로직대로 동작하기 위해선 앱을 포그라운드 서비스에 등록하는 방법이 가장 적합했다.

 

여러 블로그를 찾아보며 react-native-background-actions 라이브러리를 사용해서 구현하게 됐다.

 

728x90

 

 

코드

1. 라이브러리 다운로드

npm install react-native-background-actions

 

 

2. AndroidManifest.xml

AndroidManifest의 application 안에 서비스를 등록해준다.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    
    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="true"
      android:usesCleartextTraffic="true"
      android:theme="@style/AppTheme">
      
      ...
      
      <service android:name="com.asterinet.react.bgactions.RNBackgroundActionsTask" /> 
    </application>
</manifest>

 

 

3. 포그라운드 동작 코드

import BackgroundService from "react-native-background-actions";
import axios from "axios";
import { SERVER_URL } from "../utils/config";

const App = () => {
    ...
    
    const background = async () => {
      const sleep = (time: number) => new Promise((resolve: any) => setTimeout(() => resolve(), time));

      const veryIntensiveTask = async (taskDataArguments: any) => {
        // Example of an infinite loop task
        const { delay } = taskDataArguments;
      
        await new Promise( async (resolve) => {
          for (let i = 0; BackgroundService.isRunning(); i++) {
            await axios.post(`${SERVER_URL}/test`, {
              // 파라미터
            });
            await sleep(delay);
          }
        });
    };
  
    const options = {
      taskName: 'Example',
      taskTitle: 'Example Title',
      taskDesc: 'Example Desc',
      taskIcon: {
        name: 'ic_launcher',
        type: 'mipmap',
      },
      color: '#ff00ff',
      parameters: {
        delay: 1000 * 60 * 30,
      },
    };
  
    await BackgroundService.start(veryIntensiveTask, options);
    await BackgroundService.updateNotification({taskDesc: 'New TestTask description'});
  }

  useEffect(() => {
    if(isAndroid) {
      background();
    }
  }, []);

}

 

 

react-native-background-actions

다음은 해당 라이브러리의 git 사이트에 적혀있는 내용을 번역한 것이다.

Android
이 라이브러리는 Android용 React Native Headless JS를 사용합니다.
JS 작업을 구축하기 전에 모든 문서를 읽어보세요.
앱이 종료된 경우에도 작업은 실행됩니다.
Android 12 이상에서는 백그라운드에서 백그라운드 작업을 실행할 수 없습니다.
작업이 실행 중일 때 알림이 표시되며 알림 없이는 서비스를 시작할 수 없습니다.
알림은 Android에서만 표시됩니다.

iOS
이 라이브러리는 iOS의 UIApplication beginBackgroundTaskWithName 메소드를 사용합니다.
앱이 영원히 백그라운드에 유지되지는 않습니다.
그러나 이 라이브러리에서 JS를 실행하는 동안 오디오, 위치정보 등을 사용하는 react-native-track-player 등의 다른 라이브러리를 사용하여 앱을 백그라운드에서 활성 상태로 유지할 수 있습니다.

 

React Native의 Headless JS 라이브러리를 사용해서 백그라운드, 포그라운드 상태에서 앱을 유지시켜준다.

 

 options에서 사용한 option의 프로퍼티는 다음과 같다.

프로퍼티 타입 설명
taskName <string> task의 고유 이름을 설정한다.
taskTitle <string> 알림에 보여질 제목을 설정한다. (안드로이드 필수)
taskDesc <string> 알림에 보여질 내용을 설정한다. (안드로이드 필수)
taskIcon <taskIconOptions> 알림에 보여질 아이콘을 설정한다. (안드로이드 필수)
color <string> 알림의 글자 색을 설정한다. (기본값, #fffff)
linkingURI <string> 알림 클릭 시 연결할 링크 주소를 설정한다.
progressBar <taskProgressBarOptions> 알림의 진행 바
parameters <any> task에 전달될 파라미터 값

 

라이브러리에 대한 자세한 설명 및 예제 코드는 아래의 링크를 참고하면 된다.

https://github.com/Rapsssito/react-native-background-actions?tab=readme-ov-file

 

GitHub - Rapsssito/react-native-background-actions: React Native background service library for running background tasks forever

React Native background service library for running background tasks forever in Android & iOS. - GitHub - Rapsssito/react-native-background-actions: React Native background service library for ...

github.com

 

 

결과

정상적으로 포그라운드 서비스로 등록이 됐고, 서버 로그를 확인해 보니 30분마다 서버로 통신을 보냈다.

그림 2-1. 포그라운드 서비스 동작 상태

 

 

 

 

 

 

 

 

 

 

728x90

댓글