Android Firebase实时数据库第一次连接花费的时间太长
这里我们正在使用Firebase Relatime数据库制作一个应用程序。当我们的应用程序第一次打开时会尝试连接到firebase数据库,这需要花费大量时间。在第一次连接之后,速度非常快。我想知道如何快速建立第一次连接?在这方面,我们可以使用服务长时间运行的后台任务来解决第一次连接缓慢的问题。Android Firebase实时数据库第一次连接花费的时间太长,android,performance,firebase-realtime-database,database-connection,real-time,Android,Performance,Firebase Realtime Database,Database Connection,Real Time,这里我们正在使用Firebase Relatime数据库制作一个应用程序。当我们的应用程序第一次打开时会尝试连接到firebase数据库,这需要花费大量时间。在第一次连接之后,速度非常快。我想知道如何快速建立第一次连接?在这方面,我们可以使用服务长时间运行的后台任务来解决第一次连接缓慢的问题。 /** * Created by bipin on 1/18/17. */ public class FirstConnectionService extends Service { p
/**
* Created by bipin on 1/18/17.
*/
public class FirstConnectionService extends Service {
public static DatabaseReference databaseReference;
private static String TAG = FirstConnectionService.class.getSimpleName();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
getDriverStatus();
return START_STICKY;
}
/**
* long running background task using services
*/
private void getDriverStatus() {
try {
databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(
Constants.FIREBASE_DRIVER + "/" + 100 + "/status");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
AppUtils.showLog(TAG, "onDataChange");
}
@Override
public void onCancelled(DatabaseError databaseError) {
AppUtils.showLog(TAG, "onCancelled");
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
并通过检查服务是否已在运行来启动服务
/**
* First check if service is already running.
*/
if (!ServiceUtils.isMyServiceRunning(FirstConnectionService.class, this)) {
AppUtils.showLog("FirstConnectionService", "isMyServiceRunning: false");
startService(new Intent(this, FirstConnectionService.class));
} else {
AppUtils.showLog("FirstConnectionService", "isMyServiceRunning: true");
}
服务UTIL
/**
* Created by bipin on 1/18/17.
*/
public class ServiceUtils {
/**
* Check if service is already running in background
* */
public static boolean isMyServiceRunning(Class<?> serviceClass, Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
/**
*由bipin于2017年1月18日创建。
*/
公共类服务{
/**
*检查服务是否已在后台运行
* */
公共静态布尔isMyServiceRunning(类serviceClass,上下文){
ActivityManager=(ActivityManager)context.getSystemService(context.ACTIVITY_服务);
对于(ActivityManager.RunningServiceInfo服务:manager.getRunningServices(Integer.MAX_值)){
if(serviceClass.getName().equals(service.service.getClassName())){
返回true;
}
}
返回false;
}
}
回答博米之前,请仔细阅读问题。