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

时间:2018-08-31 08:03:14

标签: android firebase firebase-realtime-database

我想定期更新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秒重复一次?

1 个答案:

答案 0 :(得分:1)

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

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

MainActivity:

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();
    }
}

希望对您有所帮助。