- 首先,在项目的build.gradle文件中添加google-services插件依赖:
buildscript {
dependencies {
// ...其他依赖
classpath 'com.google.gms:google-services:4.3.2'
}
}
- 在app的build.gradle文件中添加以下依赖和apply插件:
dependencies {
// ...其他依赖
implementation 'com.google.firebase:firebase-core:17.4.4'
}
apply plugin: 'com.google.gms.google-services'
- 在Application的onCreate()方法中初始化Firebase:
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
FirebaseApp.initializeApp(this)
}
}
- 在代码中使用Firebase的API,如:
import com.google.firebase.analytics.FirebaseAnalytics
class MainActivity : AppCompatActivity() {
private lateinit var firebaseAnalytics: FirebaseAnalytics
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 初始化Analytics
firebaseAnalytics = FirebaseAnalytics.getInstance(this)
// 在Button的OnClickListener中记录事件
button.setOnClickListener {
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "button")
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "click")
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle)
}
}
}