Runnable不会等待功能完成

时间:2017-04-03 15:12:04

标签: java android function runnable postdelayed

我正试图为UI刷新每一分钟。 我编写了这段代码,我有一个处理程序和一个带有postdelay的runnable。在我的runnable中,我调用了一个返回Map对象的函数。但每次,在从函数中返回Map对象之前,我的runnable继续执行下一行代码。

有谁知道如何解决这个问题?

我的代码:

Handler handler = new Handler();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        Map<String, String> varList = refreshVars(firstname, lastname, id);

        String newlastdate = varList.get("newlastdate");
        String newcurrentdate = varList.get("newcurrentdate");

        /*UI changes related to "newlastdate" and "newcurrentdate"*/
    }
    handler.postDelayed(this, 60000);
}
};
handler.postDelayed(runnable, 60000);

功能:

public Map<String, String> refreshExitVars(final String FN, final String LN, final String IDN){
    final Map<String, String> list = new HashMap<>();
    Response.Listener<String> responseListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");
                if (success) {
                    String nlastdate = jsonResponse.getString("date");
                    String ncurrentdate = jsonResponse.getString("currentdate");

                    list.put("newlastdate", nlastdate);
                    list.put("newcurrentdate", ncurrentdate);
                } else {
                    int ErrorCode = jsonResponse.getInt("errorcode");
                    AlertDialog.Builder builder;
                    builder = new AlertDialog.Builder(Exit.this);
                    builder.setMessage("" + ErrorCode)
                           .setNegativeButton("Close", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    this.finish();
                                }
                            })
                           .create()
                           .show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    RequestUIChanges requestUIChanges = new RequestUIChanges(FN, LN, IDN, responseListener);
    RequestQueue queue = Volley.newRequestQueue(Exit.this);
    queue.add(requestUIChanges);

    return list;
}

1 个答案:

答案 0 :(得分:0)

正如@MohammedAtif指出的那样,您在refreshExitVars()方法中提出的请求是异步的。这就是为什么你有responseListener的原因。异步请求完成时,将调用该侦听器的onResponse()方法。

最简单的方法是将/*UI changes related to "newlastdate" and "newcurrentdate"*/移到onResponse()方法中,而不是尝试返回数据。