我希望我的Android应用能够从应用启动点开始收听Firebase数据库引用,直到应用终止。
通过在应用程序的onCreate
中的数据库引用中添加ValueEventListener并在应用程序的onTerminate
中删除它来实现所需的行为:
public class My_Application extends Application {
// The DB ref that the ValueEventListener will be added to.
DatabaseReference dbRef = V_DB.FBREF_CHATROOMS;
// Used to remove ValueEventListeners that were added in this class.
Pair<DatabaseReference, ValueEventListener> mListener;
@Override
public void onCreate() {
super.onCreate();
// Add the ValueEventListener.
ValueEventListener mValueEventListener = dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Do something here.
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Do something here.
}
});
// Store listener.
mListener = new Pair<>(dbRef, mValueEventListener);
}
@Override
public void onTerminate() {
super.onTerminate();
// Remove listener.
mListener.first.removeEventListener(mListener.second);
}
}
这似乎是显而易见的方式,但正如Application.onCreate
here所述:
实现应该尽可能快(例如使用状态的延迟初始化),因为在此函数中花费的时间直接影响在进程中启动第一个活动,服务或接收者的性能。
考虑到上述情况(并没有排除其他潜在问题),我想问一下,当你想要一个应用程序范围的ValueEventListener时,我的方法是否可行,或者是否有另一种更有效的方法。
答案 0 :(得分:0)
根据Ronak Makwana的建议,我使用了一项服务在我的SplashScreenActivity ValueEventListeners
中添加了我的全部应用范围onCreate()
。该服务已在我的SplashScreenActivity onDestroy()
中停止。在我的服务onDestroy()
中,我删除了我已添加的所有应用范围的ValueEventListener。
@Override
protected void onCreate(Bundle savedInstanceState) {
// Do other stuff
// Start service for adding App-Wide Listeners.
this.startService_AddAppwideValuEventListeners();
}
@Override
protected void onDestroy() {
super.onDestroy();
// Stop Service (by doing so, all App-Wide Listenersare removed in Service's onDestroy().
stopService(new Intent(this, Service_AddAppwideValuEventListeners.class));
}
// Start Service
private void startService_AddAppwideValuEventListeners() {
// Get Intent for starting my Service that adds some VELs.
Intent mServiceIntent = new Intent(this, Service_AddAppwideValuEventListeners.class);
// Start service (this service is stopped in Activity's onDestroy())
wCurrentContext.startService(mServiceIntent);
}
到目前为止,它的作用就像一个魅力和开销,而这样做是非常低的(因为一切都在服务中完成)。