在android应用程序处于前台时,每5秒钟更新一次状态

在android应用程序处于前台时,每5秒钟更新一次状态,android,firebase,firebase-realtime-database,Android,Firebase,Firebase Realtime Database,我想定期更新我在firebase中的联机状态,但当它在前台时,但当它在后台时,我必须将状态设置为脱机。 所以,请帮助我如何管理 下面是我在firebase上更新它的代码 private void fireStoreUpdate() { PreferenceManager preferenceManager = new PreferenceManager(getApplicationContext()); String chefId = preferenceManager.getC

我想定期更新我在firebase中的联机状态,但当它在前台时,但当它在后台时,我必须将状态设置为脱机。 所以,请帮助我如何管理

下面是我在firebase上更新它的代码

private void fireStoreUpdate() {
    PreferenceManager preferenceManager = new PreferenceManager(getApplicationContext());
    String chefId = preferenceManager.getChefId();
    String restuarantId = preferenceManager.getMerchantId();
    Restaurant restaurant = new Restaurant("online", String.valueOf(System.currentTimeMillis()), chefId, restuarantId);
    // Firestore
    FirebaseFirestore.getInstance().collection("restaurants").document("Restaurant ID : " + restuarantId).set(restaurant);
}

它正在更新,但如何使它每5秒重复一次?

您可以使用处理程序,每“x”次执行一次函数。当生命周期为onPause()时,您只需停止此处理程序,当应用程序在onResume()中返回前台时,再次执行该处理程序

我将通过一个简单的活动向您展示该方法

main活动:

public class MainActivity extends AppCompatActivity {
    private final long EVERY_FIVE_SECOND = 5000;

    private Handler handler;
    private Runnable runnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Executing the handler
        executeHandler();
    }

    private void executeHandler(){
        //If the handler and runnable are null we create it the first time.
        if(handler == null && runnable == null){
            handler = new Handler();

           runnable = new Runnable() {
                @Override
                public void run() {
                    //Updating firebase store
                    fireStoreUpdate();
                    //And we execute it again
                    handler.postDelayed(this, EVERY_FIVE_SECOND);
                }
            };
        }
        //If the handler and runnable are not null, we execute it again when the app is resumed.
        else{
            handler.postDelayed(runnable, EVERY_FIVE_SECOND);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //execute the handler again.
        executeHandler();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //we remove the callback
        handler.removeCallbacks(runnable);
        //and we set the status to offline.
        updateStatusToOffline();
    }
}

我希望这对你有帮助

看看这个链接。它向您展示了如何使用FirebaseJobDispatcher计划作业并每N秒重复一次。使用
LifecycleObserver
并每5秒调用一次此方法。您可以使用
计时器
。谢谢,我将尝试.ADM如何使用LifecycleObserver执行此重复任务?但当我停留在该活动中时,它会工作,但如果我将其移动到另一个活动中,它将不工作。我真的想要我的申请表。我刚刚在我的应用程序类中使用了这段代码,它正在工作。你好,Shubham Dubey。我写了一篇关于在应用程序类中使用它的文章。谢谢兄弟,它正在工作,但我如何才能以更好的方式改进它?有什么建议吗?我认为另一种方法可以是使用作业调度器,在应用程序工作时执行它,在应用程序不工作时终止它:FirebaseJobDispatcher是一个很好的库。