gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 23:37:30 24 4
gpt4 key购买 nike

我想定期更新我在 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() 中返回前台时再次执行处理程序。

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

主要 Activity :

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

希望对您有所帮助。

关于android - 当应用程序在 android 中处于前台时,每 5 秒更新一次状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52111069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com