问题描述
我正在使用Firebase创建一个小聊天应用程序。我想 ChildEventListener
继续监听firebase数据库的位置,尽管我的应用程序在后台或退出。目前我正在注册它,当我的应用程序退出或关闭使用 finish()
之后,我的ChildEventListener的方法都没有被调用像 onChildAdded
或 onChildChanged
虽然我没有调用 removeEventListener
。我想让ChildEventListener一直运行背景。有没有这样做?使用服务来收听您的ChildEventListener
public class ChildEventListener extends Service {
@Override
public IBinder onBind(Intent intent){
return null;
@Override
public int onStartCommand(Intent intent,int flags,int startId){
//将一个childevent侦听器添加到firebase
Firebase myFirebaseRef = new Firebase ( FirebaseURL);
myFirebaseRef.child(FIREBASE_LOCATION)。addValueEventListener(new ValueEventListener(){
$ b @Override
public void onDataChange(DataSnapshot snapshot){
//使用DataSnapshot说调用通知
$ b $ @覆盖$ b $公共无效onCancelled(FirebaseError错误){
Log.e(读取失败:,error.getMessage ());
}
});
$覆盖
public void onCancelled(FirebaseError firebaseError){
Log.e(The read failed:,firebaseError.getMessage ));
}
});
return START_STICKY;
$ b $ / code $ / $ p
注册你的服务在Manifest p>
< service android:name =。ChildEventListener/>开始你的服务,并听取childEvents,开始你的服务的地点/时间取决于你的聊天应用程序设计
I am using Firebase for creating a small chat application. I want ChildEventListener
to keep listening to the firebase database location though my app is in background or it is exited. Currently I am registering it and when my app exits or closed using finish()
, after that none of my methods of ChildEventListener are getting called like onChildAdded
or onChildChanged
though I haven't called removeEventListener
.I want ChildEventListener to be always running in background. Is there anyway of doing that?
解决方案 Use service to listen your ChildEventListener
public class ChildEventListener extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Adding a childevent listener to firebase
Firebase myFirebaseRef = new Firebase("FirebaseURL");
myFirebaseRef.child("FIREBASE_LOCATION").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
//Do something using DataSnapshot say call Notification
}
@Override
public void onCancelled(FirebaseError error) {
Log.e("The read failed: ", error.getMessage());
}
});
}
@Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("The read failed: ", firebaseError.getMessage());
}
});
return START_STICKY;
}
}
register your Service inside Manifest
<service android:name=".ChildEventListener "/>
Start your Service and listen for childEvents, where/when to start your service is up to your chat app design
这篇关于Firebase:通过应用程序退出来继续收听ChildEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!