はじめに
WebからAndroidに入るような人って、まず、Androidの端末からHelloWorldを、Firebaseに送りたいのよ。なんでかQiitaにもUdemyにもTechpitにもシンプルにミニマルに書いてあるってないのよー
前提条件
全部最新版でいい(とりあえず)
・AndroidStudioは一番新しいのを入れろ
・Targets API level 16+ を入れろ
・Uses Gradle 4.1+ を入れろ
・Uses Jetpack (AndroidX) を入れろ
・compileSdkVersion 28+ を入れろ
Androidプロジェクト作成
Create New Project
Empty Activity
画面の表示や説明を見てつぎのステップが予想できるようになることが肝要だ
Name: HelloFirebase
Package name: com.yoshi.hellofirebase
アプリケーションIDとは
Language: Kotlin
SDK: API30
(IDE上からエミュレータがダウンロードできる)
確認
プロジェクトが作られた瞬間、Androidとしての最低限の動きはしてくれる
Add Firebase to your Android project
参考(公式): Add Firebase using the Firebase console
Step1: Firebaseプロジェクトを作成
Firebase console
googleアナリティクスアカウント持ってる人は指定して
Firebaseプロジェクト作成中!
Step2: Register your app with Firebase
Android パッケージ名: com.yoshi.hellofirebase
アプリのニックネーム: hellofirebase
デバッグ用の署名証明書 SHA-1: *****(以下参照)
AndroidStudioProjects\HelloFirebase> ./gradlew signingReport
SHA1: 64:D5:B8:9A:D6:72:2B:6E:3B:DF:22:81:AE:6B:AF:BF:B6:B6:EE:55
設定ファイル(google-services.json)のダウンロードと配置
もう書いてあるとおりなんだけど Project 表示に切り替えて app フォルダ配下に設定ファイルを移動。次へボタン
Step3: Firebase SDK の追加
Gradle 用の Google サービス プラグインは、ダウンロードした google-services.json
ファイルを読み込みます。このプラグインを使用するよう、build.gradle
ファイルを修正。
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
...
// Add this line
+ classpath 'com.google.gms:google-services:4.3.5'
}
}
allprojects {
...
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
...
}
}
plugins {
id 'com.android.application'
id 'kotlin-android'
+ id 'com.google.gms.google-services'
}
dependencies {
// Import the Firebase BoM
+ implementation platform('com.google.firebase:firebase-bom:26.7.0')
// Add the dependency for the Firebase SDK for Google Analytics
+ implementation 'com.google.firebase:firebase-analytics-ktx'
}
Gradle sync
Connect your App to Firebase
Create a Database
Firebase console
認証モードでやれたほうがいいけどとりあえず文字突っ込みたいだけなのでテストモードで
とりあえず null レコードが表示されているらしい
Add the Realtime Database SDK to your app
dependencies {
// Import the Firebase BoM
implementation platform('com.google.firebase:firebase-bom:26.7.0')
+ implementation 'com.google.firebase:firebase-database-ktx'
}
Write to your database
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
+ val database = Firebase.database
+ val myRef = database.getReference("message")
+ myRef.setValue("Hello, World!")
}
}
確認
赤くなってたら単純なimportエラーなのでimportしましょう
モニターしてるとリアルタイムで変わることを確認しよう