每 x 秒重复 Volley 请求 Java

Repeat Volley Request Every x-seconds Java

好的 - 在你说这是重复之前,我已经查看了我能找到的每篇堆栈溢出文章,其中 none 有效 and/or 回答了问题 properly/simply .我所需要的只是每隔 x 秒重复一个带有 volley 请求的函数。

基本上,我在一个函数中有一个相当简单的 Volley 请求,它在一次调用中绝对完美。

排球功能:

  private void SetBusPositions() {
        TextView textE = (TextView) findViewById(R.id.FirstInfo);
        RequestQueue Queue = ServerRequestsQueue.getInstance(context.getApplicationContext()).getRequestQueue();
        int SendMethod = Request.Method.GET;
        String ServerURL = "my url";
        JsonArrayRequest JOR = new JsonArrayRequest(SendMethod, ServerURL, null, new Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray resp) {
                textE.setText(resp.toString());
                System.out.println("Response is: " + resp.toString());
                //for each object in JSON Array
                for (int i = 0; i < resp.length(); i++) {
                }
            }
        }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
             //process
            }
        });
        Queue.add(JOR);
    }

我只想定期调用此函数,从服务器接收数据并更新我的总线位置数据。必须有一个相当简单的方法来做到这一点?我知道我一定遗漏了一些东西,但 none 的其他答案似乎有所帮助。

此外,由于我正在使用 Google 地图,所以我的 class 已经在扩展 FragmentActivity。我已经看到扩展 Runnable 以使其工作的方法——但我的 Java 在这里有点生疏。我一直在做太多的JS。

private final class RepeatedOperation extends AsyncTask<Map, Void, String> {

    @Override
    protected String doInBackground(Map... params) {
    
        SetBusPosition(params[0]);

    }

    @Override
    protected void onPostExecute(String result) {
    }
}


private void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {       
    @Override
    public void run() {
        handler.post(new Runnable() {
            public void run() {       
                try {
                    RepeatedOperation performBackgroundTask = new RepeatedOperation();
                    // RepeatedOperation this class is the class that extends AsyncTask 
                    performBackgroundTask.execute(map);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                }
            }
        });
    }
};
timer.schedule(doAsynchronousTask, 0, 50000); //execute in every 50000 ms
}

试一试并将其添加到与 SetBusPosition() 相同的范围内