我正在使用Firebase创建一个小型聊天应用程序。我希望ChildEventListener
继续监听firebase数据库位置,尽管我的应用程序处于后台或退出。目前我正在注册它,当我的应用程序使用finish()
退出或关闭时,之后我的所有ChildEventListener方法都没有调用onChildAdded
或onChildChanged
,尽管我没有调用{{ 1}}。我希望ChildEventListener始终在后台运行。无论如何都这样做?
答案 0 :(得分:9)
使用服务来监听您的ChildEventListener
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
command.CommandText = @"
insert into YourTable (facility,rank) values ('classroom',@classroomRank);
insert into YourTable (facility,rank) values ('labs',@labsRank);
insert into YourTable (facility,rank) values ('lib',@libRank);
insert into YourTable (facility,rank) values ('Cleanliness',@cleanlinessRank);
command.Connection = connection;
command.ExecuteNonQuery();
}
在清单中注册您的服务
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;
}
}
启动您的服务并收听childEvents,在何处/何时启动您的服务取决于您的聊天应用设计
答案 1 :(得分:0)
尝试使用具有Firebase功能的Firebase云消息传递。