【问题标题】:Firebase Realtime Database is taking too much time for the first time connectionFirebase 实时数据库第一次连接花费了太多时间
【发布时间】:2017-06-02 08:52:58
【问题描述】:

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

【问题讨论】:

  • 请在回答Bhoomi之前仔细阅读问题

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


【解决方案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;
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2013-07-11
    相关资源
    最近更新 更多