본문 바로가기
개발/안드로이드

[안드로이드] 파이어베이스 Remote Config 사용기

by 핸디(Handy) 2020. 6. 14.

자체 서버가 없는 서비에서 갑작스런 키값의 변경, 특정 값을 모바일 앱에 전달해야하는 상황은 매우 당혹스럽기마련입니다. 값을 주자니 앱을 업데이트 해야하는데 간단한 문자열 변경을 위해 업데이트 하는 것도 부담스럽기 때문이죠.

이런 상황을 안타깝게 여기신 갓갓님들이 만들어주신 기능이 원격 설정 ( Remote Config ) 입니다.

제가 주로 사용하는 파이어베이스에서도 원격 설정 기능을 제공하고 있어 이렇게 사용기를 작성합니다.

파이어베이스 Remote Config의 기능은 크게 3가지로 볼 수 있습니다.
1. 앱의 변경사항을 사용자에게 빠르게 적용시키기
2. 사용자 분류를 통한 맞춤 설정
3. A/B 테스트를 통한 개선

이 중에 이번 포스트에서는 1번. 앱의 변경사항을 사용자에게 빠르게 적용시키기에 대해 살펴보겠습니다.

2020/06/02 - [개발/안드로이드] - [안드로이드] 앱 업데이트를 관리하는 방법 #1

 

[안드로이드] 앱 업데이트를 관리하는 방법 #1

안드로이드 앱을 업데이트 하는 방법은 2가지로 나뉩니다. 1. 유저가 알아서 언젠가 하길 기다리기 2. 개발자가 앱 실행시 판단해서 강제로 하기 여기서 우리는 2번째에 해당하는 경우에 대해 2가

all-dev-kang.tistory.com

이전 글에서 쓰인 remote config를 이용한 앱 업데이트 관리에 쓰인 기능입니다.

그럼 구현 내용을 설명하도록 하겠습니다. 기본적인 연동의 경우 클릭 몇번이면 자동으로 해주기 때문에 여기선 생략하겠습니다.


파이어베이스 콘솔창에 들어가서 왼쪽 하단을 보면 다음과 같은 기능이 있습니다. 저번 포스트에서는 FCM인 Cloud Messaging 을 사용해봤으며 이번에는 그 아래에 있는 Remote Config를 사용하겠습니다.

매개변수 키와 기본값을 입력하고 매개변수 추가를 눌려주시면 몇초? 이내에 적용이됩니다,

이제 어플리케이션 구현쪽으로 넘어가겠습니다.

  final FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
        FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
                .build();
        firebaseRemoteConfig.setConfigSettingsAsync(configSettings);
        firebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_default);
        firebaseRemoteConfig.fetch()
                .addOnCompleteListener(this, task -> {
                    if(task.isSuccessful()){
                        firebaseRemoteConfig.activate();
                        String remoteConfig  = firebaseRemoteConfig.getString("test_parameter")
                     
                });

이렇게 선언해주신다면 remoteConfig 에 설정한 기본값인 default_value 가 들어갑니다.

매개변수는 사용자가 원하는 갯수만큼 추가할수 있습니다. 

마지막으로 remote config를 사용하기 위해서 xml에 새로운 파일을 넣어야합니다.

<?xml version="1.0" encoding="utf-8"?>
<defaultMap>
    <entry>
        <key>test_parameter</key>
        <value>0</value>
    </entry>
</defaultMap>

바로 default 값들인데요. 만약 Remote Config가 동작하지 않을때를 대비하는 것입니다.

저의 경우 Remote Config가 정상적으로 작동할 경우 값을 받아오고 PreferenceManager 를 통해 해당 키로 값을 갱신합니다.

만약 실패했을때는 기존의 PreferenceManager에 있던 값을 그대로 가져와 사용합니다.

일반적으로 파이어베이스에 나온 값을 바로 사용하지 않습니다. 가끔씩 NPE이 떠버리는 경우가 생겨서 그렇습니다.

따라서 요약하자면

Remote Config 값 가져옴
-> PreferenceManager 에 키값으로 값 갱신

PreferenceManager.setString(getApplicationContext(), 
"test_parameter", 
firebaseRemoteConfig.getString("test_parameter"));


-> 사용하고자 하는 곳에서 PreferenceManager키값으로 호출하여 사용

String remoteConfig =  PreferenceManager.getString(getApplicationContext(), "test_parameter");

여기서 PreferenceManager는 sharePreference를 쉽게 쓰기 위해 만든 클래스입니다.

import android.content.Context;
import android.content.SharedPreferences;

public class PreferenceManager {
    public static final String PREFERENCES_NAME = "rebuild_preference";

    private static final String DEFAULT_VALUE_STRING = "";
    private static final boolean DEFAULT_VALUE_BOOLEAN = false;
    private static final int DEFAULT_VALUE_INT = -1;
    private static final long DEFAULT_VALUE_LONG = -1L;
    private static final float DEFAULT_VALUE_FLOAT = -1F;

    private static SharedPreferences getPreferences(Context context) {
        return context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
    }

    /**
     * String 값 저장
     *
     * @param context
     * @param key
     * @param value
     */

    public static void setString(Context context, String key, String value) {

        SharedPreferences prefs = getPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(key, value);
        editor.apply();

    }

    /**
     * boolean 값 저장
     *
     * @param context
     * @param key
     * @param value
     */

    public static void setBoolean(Context context, String key, boolean value) {

        SharedPreferences prefs = getPreferences(context);

        SharedPreferences.Editor editor = prefs.edit();

        editor.putBoolean(key, value);

        editor.apply();

    }


    /**
     * int 값 저장
     *
     * @param context
     * @param key
     * @param value
     */

    public static void setInt(Context context, String key, int value) {

        SharedPreferences prefs = getPreferences(context);

        SharedPreferences.Editor editor = prefs.edit();

        editor.putInt(key, value);

        editor.apply();

    }


    /**
     * long 값 저장
     *
     * @param context
     * @param key
     * @param value
     */

    public static void setLong(Context context, String key, long value) {

        SharedPreferences prefs = getPreferences(context);

        SharedPreferences.Editor editor = prefs.edit();

        editor.putLong(key, value);

        editor.apply();

    }


    /**
     * float 값 저장
     *
     * @param context
     * @param key
     * @param value
     */

    public static void setFloat(Context context, String key, float value) {

        SharedPreferences prefs = getPreferences(context);

        SharedPreferences.Editor editor = prefs.edit();

        editor.putFloat(key, value);

        editor.apply();

    }


    /**
     * String 값 로드
     *
     * @param context
     * @param key
     * @return
     */

    public static String getString(Context context, String key) {

        SharedPreferences prefs = getPreferences(context);

        String value = prefs.getString(key, DEFAULT_VALUE_STRING);

        return value;

    }


    /**
     * boolean 값 로드
     *
     * @param context
     * @param key
     * @return
     */

    public static boolean getBoolean(Context context, String key) {

        SharedPreferences prefs = getPreferences(context);

        boolean value = prefs.getBoolean(key, DEFAULT_VALUE_BOOLEAN);

        return value;

    }


    /**
     * int 값 로드
     *
     * @param context
     * @param key
     * @return
     */

    public static int getInt(Context context, String key) {

        SharedPreferences prefs = getPreferences(context);

        int value = prefs.getInt(key, DEFAULT_VALUE_INT);

        return value;

    }


    /**
     * long 값 로드
     *
     * @param context
     * @param key
     * @return
     */

    public static long getLong(Context context, String key) {

        SharedPreferences prefs = getPreferences(context);

        long value = prefs.getLong(key, DEFAULT_VALUE_LONG);

        return value;

    }


    /**
     * float 값 로드
     *
     * @param context
     * @param key
     * @return
     */

    public static float getFloat(Context context, String key) {

        SharedPreferences prefs = getPreferences(context);

        float value = prefs.getFloat(key, DEFAULT_VALUE_FLOAT);

        return value;

    }


    /**
     * 키 값 삭제
     *
     * @param context
     * @param key
     */

    public static void removeKey(Context context, String key) {

        SharedPreferences prefs = getPreferences(context);

        SharedPreferences.Editor edit = prefs.edit();

        edit.remove(key);

        edit.apply();

    }


    /**
     * 모든 저장 데이터 삭제
     *
     * @param context
     */

    public static void clear(Context context) {

        SharedPreferences prefs = getPreferences(context);

        SharedPreferences.Editor edit = prefs.edit();

        edit.clear();

        edit.apply();

    }

}

 하나 만들어두면 쉽게쉽게 쓸수 하나 만들어놓고 사용합니다. 

댓글