Firebase实时数据库第一次连接耗费了太多时间

时间:2017-01-18 04:53:07

标签: android performance firebase-realtime-database database-connection real-time

我们正在使用 Firebase Relatime数据库制作应用。当我们的应用首次打开时,它会尝试连接到firebase数据库,这需要批次到时间。在第一次连接之后它真的很快。我想知道如何第一次快速建立连接?

1 个答案:

答案 0 :(得分:1)

在此我们可以使用 SERVICE 长时间运行的后台任务来解决第一次慢速连接问题。

/**
 * 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");

    }

服务实用程序

/**
 * 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;
    }

}