Обновлять статус каждые 5 секунд, когда приложение на переднем плане в Android - PullRequest
0 голосов
/ 31 августа 2018

Я хочу периодически обновлять свой онлайн-статус в 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 голосов
/ 31 августа 2018

Вы можете использовать обработчик и выполнять свою функцию каждый раз «х». Когда жизненный цикл - 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();
    }
}

Надеюсь, это поможет вам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...