0

我目前每 5 秒检查一次我从后端获得的响应状态。

这是我的代码:

void getBookingInfo() {
            WebApi client = ServiceGenerator.createService(WebApi.class);
           final Call<BaseResponse <List<MemberBookingInfo>>> call = client.getBookingInfo(queries);
           call.enqueue(new Callback<BaseResponse<List<MemberBookingInfo>>>() {
               @Override
               public void onResponse(Call<BaseResponse<List<MemberBookingInfo>>> call, Response<BaseResponse<List<MemberBookingInfo>>> response) {
                    if (response.isSuccessful()) {
                                  if (checkIfAccepted(response.body().data.get(response.body().data.size()-1).status)){
                                        showBookedDialog(response.body().data.get(response.body().data.size()-1));
                        }

               @Override
               public void onFailure(Call<BaseResponse<List<MemberBookingInfo>>> call, Throwable t) {
                    Log.d("ERROR", "" + t.getMessage());
               }
           });

        }
    }

这是我的计时器,再次运行预订信息 5 秒

boolean checkIfAccepted(int status){
    if (status == 1){
        return  true;
    }
       hourglass = new Hourglass(5000, 1000) {
            @Override
            public void onTimerTick(long timeRemaining) { // Update UI
            }

            @Override
            public void onTimerFinish() { // Timer finished
                getBookingInfo();
            }
        };
        if (!hourglass.isRunning()) {
            hourglass.startTimer();
        }
     return  false;
    }

如果满足我的条件,沙漏应该停止并且这个对话框应该显示:

public void showBookedDialog(final MemberBookingInfo memberBookingInfo){
        listener.stopBooking();
        dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCancelable(false);
        dialog.setContentView(R.layout.dialog_booking);
        if(!((Activity) context).isFinishing()) {
            if (dialogShowing) {
                dialog.show();
                dialogShowing = true;
            }
        }

问题是: 1. 我的活动显示大约 5 - 10 叠对话框。2. 我正在寻找一种更好的方法来每 5 秒调用一次方法而不消耗太多内存

4

1 回答 1

0

您是否考虑过使用 Handler 和 Runnable?像这样:

private int handler_time = 5000 //5 seconds in milliseconds
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {

    @Override
    public void run() {
        //Your function
        getBookingInfo();
        if(YourCondition){
            //showBookedDialog()
        }else{
            //restarting the runnable
            handler.postDelayed(this, handler_time);
        }
    }

};

要启动可运行文件,只需调用

handler.post(runnable);

并结束它

handler.removeCallbacks(runnable);

您还可以添加一个全局变量,该变量存储有关对话框状态的布尔值(即对话框是否显示)并创建一个条件,其中

if(!dialogIsShowing){
    //showBookedDialog()
}

关闭对话框时,将该变量设置为false

于 2019-09-06T10:16:04.503 回答