Android:如何使用signInWithCustomToken自动诱使Firestore并监听/观察特定集合中的文档更改
我知道如何使用signInWithCustomToken进行自动验证,但我不知道如何在Android中侦听/观察文档更改。我知道如何做它的角度,所以我将粘贴贝娄只是举例说明 如果我关闭Firestore规则验证,我可以使用Android:如何使用signInWithCustomToken自动诱使Firestore并监听/观察特定集合中的文档更改,android,firebase,kotlin,google-cloud-firestore,firebase-security,Android,Firebase,Kotlin,Google Cloud Firestore,Firebase Security,我知道如何使用signInWithCustomToken进行自动验证,但我不知道如何在Android中侦听/观察文档更改。我知道如何做它的角度,所以我将粘贴贝娄只是举例说明 如果我关闭Firestore规则验证,我可以使用 val db = FirebaseFirestore.getInstance() db.collection("transfer") .get() .addOnSuccessListener { result -> for (docume
val db = FirebaseFirestore.getInstance()
db.collection("transfer")
.get()
.addOnSuccessListener { result ->
for (document in result) {
Log.d(TAG, "${document.id} => ${document.data}")
}
}
.addOnFailureListener { exception ->
Log.w(TAG, "Error getting documents.", exception)
}
但我需要在Firestore中保持Auth正常运行
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, update, write: if request.auth.uid != null;
}
}
}
我知道如何在Android中使用CustomToken进行连接
lateinit var auth: FirebaseAuth// ...
auth = FirebaseAuth.getInstance()
auth.signInWithCustomToken("eyJhbGc
*** a valid customtoken *** Wi3KcvX4ILYN7kWySB4uuDtoNE_rIvXvD7VOpvCuLZ65d5lJHTBRhfAKJMiKyokQbWTZQ1GkQ")
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCustomToken:success")
val user = auth.currentUser
//updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCustomToken:failure", task.exception)
Toast.makeText(baseContext, "Authentication failed.",
Toast.LENGTH_SHORT).show()
//updateUI(null)
}
}
但我在FirebaseAuth中看不到允许我设置集合和listen/obeser/snapshot以利用Firestore的真实数据库功能进行更改的方法
为了举例说明我在Android/Kotlin中所做的工作,下面是我如何使用Angular快照和customtoken成功实现它的
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';
import 'rxjs/Rx';
import { AngularFireAuth } from '@angular/fire/auth';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
public transfers: Observable<any[]>;
transferCollectionRef: AngularFirestoreCollection<any>;
constructor(public auth: AngularFireAuth, public db: AngularFirestore) {
this.listenSingleTransferWithToken();
}
async listenSingleTransferWithToken() {
await this.auth.signInWithCustomToken("ey *** valid customtoken *** daG1Q");
this.transferCollectionRef = this.db.collection<any>('transfer', ref => ref.where("id", "==", "1"));
this.transfers = this.transferCollectionRef.snapshotChanges().map(actions => {
return actions.map(action => {
const data = action.payload.doc.data();
const id = action.payload.doc.id;
return { id, ...data };
});
});
}
***编辑
***找到当前解决方案。由于这是我在Firestore/Android中的第一个项目,任何推荐都将不胜感激。顺便说一句,这是有效的:
package com.example.demo
//https://developer.android.com/training/basics/firstapp/starting-activity
//https://firebase.google.com/docs/firestore/quickstart#kotlin+ktx
// Tutorial to CustomToken
//https://firebase.google.com/docs/auth/android/custom-auth#kotlin+ktx
//Tutorial to Snatshot Listeners and its queries
//https://firebase.google.com/docs/firestore/query-data/listen#kotlin+ktx
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
class MainActivity : AppCompatActivity() {
lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
val TAG = "MainActivity"
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = FirebaseAuth.getInstance()
auth.signInWithCustomToken("eyJ **** uXa-CSuHUrg")
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Log.d(TAG, "*** signInWithCustomToken:success")
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCustomToken:failure", task.exception)
Toast.makeText(
baseContext, "Authentication failed.",
Toast.LENGTH_SHORT
).show()
}
}
//val db = FirebaseFirestore.getInstance()
FirebaseFirestore.getInstance().collection("transfer")
.whereEqualTo("id", "1")
.addSnapshotListener { value, e ->
if (e != null) {
Log.w(TAG, "Listen failed.", e)
return@addSnapshotListener
}
val transfer = ArrayList<String>()
for (doc in value!!) {
doc.getString("status")?.let {
transfer.add(it)
}
}
// for (document in value) {
// Log.d(TAG, "${document.id} => ${document.data}")
// }
Log.d(TAG, "*** transfer: $transfer")
}
}
}
目前的工作方案:
对于身份验证和自定义令牌,您可以在使用Kotlin的Android上查看以下内容。另一个将向您展示如何在CloudFireStore中使用Kotlin实现任何实时更新的侦听器。希望能有帮助。@sllopis,谢谢,但我还是被卡住了。如果您注意到我的问题,这表明我知道如何使用CustomToken auth.signInWithCustomToken.addOnCompleteListener登录,但我可以添加快照侦听器。我需要一些方法,比如在我使用CustomToken登录后进行快照更改,而您建议的两个链接都没有显示出来how@sllopis我刚刚从Android Studio添加了一个打印屏幕,显示CustomToken有效且已登录。但是倾听/观察/快照是如何改变收藏文档的呢?@sllopis非常感谢你。经过多次尝试,我终于成功了。我可以请你看看我是不是在做什么奇怪的事吗?首先,我使用FirebaseAuth.getInstance.signInWithCustomTokenmy cutsomtoken.addOnCompleteListener,其次使用FirebaseAuth.getInstance.collectiontransfer.whereEqualToid,1.addSnapshotListener。考虑到Firestore Customtoken的最佳实践,您是否看到了一些奇怪的事情?请参阅上面的完整代码。也许你可以将你的第一个评论设置为答案,这样我就可以选择它了。我很高兴你让它工作了。signInWithCustomToken方法和addSnapshotListener observable看起来都不错。顺便说一句,我发布了你当前的工作代码作为答案,所以其他用户可以从这篇文章中受益。谢谢
package com.example.demo
//https://developer.android.com/training/basics/firstapp/starting-activity
//https://firebase.google.com/docs/firestore/quickstart#kotlin+ktx
// Tutorial to CustomToken
//https://firebase.google.com/docs/auth/android/custom-auth#kotlin+ktx
//Tutorial to Snatshot Listeners and its queries
//https://firebase.google.com/docs/firestore/query-data/listen#kotlin+ktx
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
class MainActivity : AppCompatActivity() {
lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
val TAG = "MainActivity"
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = FirebaseAuth.getInstance()
auth.signInWithCustomToken("eyJ **** uXa-CSuHUrg")
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
Log.d(TAG, "*** signInWithCustomToken:success")
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCustomToken:failure", task.exception)
Toast.makeText(
baseContext, "Authentication failed.",
Toast.LENGTH_SHORT
).show()
}
}
//val db = FirebaseFirestore.getInstance()
FirebaseFirestore.getInstance().collection("transfer")
.whereEqualTo("id", "1")
.addSnapshotListener { value, e ->
if (e != null) {
Log.w(TAG, "Listen failed.", e)
return@addSnapshotListener
}
val transfer = ArrayList<String>()
for (doc in value!!) {
doc.getString("status")?.let {
transfer.add(it)
}
}
// for (document in value) {
// Log.d(TAG, "${document.id} => ${document.data}")
// }
Log.d(TAG, "*** transfer: $transfer")
}
}
}