简体   繁体   English

显示用户离线的最佳方式 - Firebase Android

[英]Best way to show user is offline - Firebase Android

I am developing an app in which the presence status of the user must be visible to other users.我正在开发一个应用程序,其中用户的在线状态必须对其他用户可见。 Following this tutorial I built the following code in my first activity按照本教程,我在第一个活动中构建了以下代码

override fun onStart() {
    super.onStart()
    val database = FirebaseDatabase.getInstance()

    val lastOnlineRef = database.getReference("/usuarios/${UsuarioFirebase.getId()}/status")

    val connectedRef = database.getReference(".info/connected")
    connectedRef.addValueEventListener(object : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            val connected = snapshot.getValue(Boolean::class.java) ?: false
            if (connected) {

                lastOnlineRef.setValue("online")

                lastOnlineRef.onDisconnect().setValue(System.currentTimeMillis().toString())

            } else {
                Log.d("ONLINE", "not connected")
            }
        }

        override fun onCancelled(error: DatabaseError) {
            Log.w("ONLINE", "Listener was cancelled at .info/connected")
        }
    })
}

The code works fine when closing the app, saving the time the app was last active.该代码在关闭应用程序时工作正常,节省了应用程序上次处于活动状态的时间。 However when opening another app and my app is in the background, firebase shows my user as "online".但是,当打开另一个应用程序并且我的应用程序在后台时,firebase 将我的用户显示为“在线”。

Maybe I should indicate that the user is offline in the onPause () method of each actvity, but my app has a lot of actvities.也许我应该在每个actvity的onPause()方法中指明用户离线,但是我的app有很多actvities。 What is the best way to solve this problem?解决这个问题的最佳方法是什么?

Best way to handle such a scenario is to use ActivityLifecycleHandler处理这种情况的最佳方法是使用ActivityLifecycleHandler

Below is the example which must be extended by Application Class下面是必须由应用程序类扩展的示例

Hope it will answer your question希望它能回答你的问题

Note: I made this to track start and resume, similarly you can have it for pause state注意:我做这个是为了跟踪开始和恢复,同样你可以将它用于暂停状态


    private LifecycleListener listener;
    private int started;
    private int resumed;

    public ActivityLifecycleHandler(LifecycleListener listener) {
        this.listener = listener;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle bundle) {
    }

    @Override
    public void onActivityStarted(Activity activity) {
        if (started == 0 && listener != null) {
            listener.onApplicationStarted();
        }
        started++;
    }

    @Override
    public void onActivityResumed(Activity activity) {
        resumed++;
    }

    @Override
    public void onActivityPaused(Activity activity) {
        resumed--;
    }

    @Override
    public void onActivityStopped(Activity activity) {
        started--;
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
    }

    /**
     * Informs the listener about application lifecycle events.
     */
    public interface LifecycleListener {
        /**
         * Called right before the application is stopped.
         */
        void onApplicationStopped();

        /**
         * Called right after the application has been started.
         */
        void onApplicationStarted();

        /**
         * Called when the application has gone to the background.
         */
        void onApplicationPaused();

        /**
         * Called right after the application has come to the foreground.
         */
        void onApplicationResumed();
    }
}

You can tell firebase to go offline in your onStop method您可以在 onStop 方法中告诉 firebase 离线

    FirebaseDatabase.getInstance().goOffline();

Again, go online in your onResume method再次,在你的 onResume 方法中上线

    FirebaseDatabase.getInstance().goOnline();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM