1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Kotlin】FirebaseのRemote Configを使ってみる

Last updated at Posted at 2020-10-22

はじめに

Androidアプリを作っていると変数を外部から操作したい事ってあると思うのですが、今回FirebaseのRemoteConfigを使って実装してみました。
初めて使ってみてとても簡単に実装できたので、今更感はあるかと思いますが備忘録として残しておこうと思います。
おかしなところなどあったらツッコミお願いします!

※Firebaseの導入部分は割愛しますので必要に応じてお調べください。

準備

ライブラリを追加
build.gradle(Module.app)
dependencies{
      implementation 'com.google.firebase:firebase-config-ktx:19.2.0'//追加
}
Firebase側の設定

コメント 2020-10-19 142446.png
パラメータキーと受け取る値を設定します。受け取る値には色々と条件を設定することも可能です。
また、Firebaseの他のサービスと違い、これらは後から編集や削除が自由にできます(全部そうして欲しい)。

構成

MainActivity.kt:Firebaseから受け取ったデータを表示するだけ
activity_main.xml
remote_config_defaults.xml:Firebaseからのfetchに失敗したとき用のデフォルト値を設定するファイル

レイアウト

activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackground"
    tools:context=".MainActivity">

    <TextView
            android:id="@+id/rc_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:text="Now Loading"
            android:textSize="20sp"
            android:textColor="@color/colorText"/>

</androidx.constraintlayout.widget.ConstraintLayout>

今回はテキストを表示するだけです。
Firebaseとの通信中等はandroid:textに設定した値が表示されます(一瞬ですが)。

デフォルト設定ファイル

res/xml内にファイルを作成します。

remote_config_defaults.xml
<defaultsMap>
    <entry>
        <key>remote_config_text</key>
        <value>RemoteConfigからの受信に失敗しました。</value>
    </entry>
</defaultsMap>

keyにはFirebase側で設定したパラメータキーと同じ値を設定します。
valueには何らかの理由でFirebaseから値を受け取れなかった時用のデフォルト値を設定します。

実装

MainActivity.ky
class MainActivity : AppCompatActivity() {

    private lateinit var rc_text:TextView
    private lateinit var remoteConfig: FirebaseRemoteConfig

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        rc_text = findViewById(R.id.rc_text)
        remoteConfig = Firebase.remoteConfig

        //開発用
        val configSettings = remoteConfigSettings {
            minimumFetchIntervalInSeconds = 3600//最小fetch間隔(s)
        }
        remoteConfig.setConfigSettingsAsync(configSettings)
        //開発用

        remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)//デフォルト設定用ファイル

        remoteConfigFetch()
    }

    private fun remoteConfigFetch(){
        remoteConfig.fetchAndActivate().addOnCompleteListener(this){task ->
            if(task.isSuccessful){
                //fetch成功
                rc_text.text = remoteConfig.getString("remote_cofig_text")
            }else{
                //fetch失敗
                Toast.makeText(applicationContext, R.string.msg_error_fetch, Toast.LENGTH_SHORT).show()
            }
            rc_text.text = remoteConfig.getString("remote_cofig_text")
        }
    }
}

通常は前回のfetchから12時間以上経過しないと次のfetchは行われないようなので頻繁に更新が必要な場合には不向きです。
開発時はminimumFetchIntervalInSecondsを3600に設定すれば1時間おきにfetchできるようになります(それでも長いですが)。
あとはリスナーでfetch成功とfetch失敗を受けていますが、いずれの場合もgetStringしてます。こうすることでfetchできればFirebaseに設定した値に、失敗したらデフォルト値(またはキャッシュしていればその値)になります。

おしまい

12時間おきの制限があるとはいえ、これを無料で使えるのはありがたいですよね。
しかもFirebaseのサービスは本当に簡単に実装することができるので、やりたいことが色々でてきます。
このRemoteConfigも本来はA/Bテストや強制アップデートなんかに使うことが多いみたいですが、他にも沢山使い道がありそうです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?