在Android中使用计时器反复运行请求

问题描述 投票:0回答:1

我正在寻找一种与监听器重复运行此任务的方法。目前,这是可行的,但我正在寻找一种每10秒重复进行一次的方法。

活动

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        VolleyRequest.makeRequest(this, URL, listenerResponse, listenerError);

    }

    private static final String URL = "https://naqil.ma/random.php";
    private Response.Listener<JSONObject> listenerResponse = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Toast.makeText(SecondActivity.this, "Resonse " + response.toString(), Toast.LENGTH_LONG).show();
        }
    };

    private Response.ErrorListener listenerError = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(SecondActivity.this, "Error " + error, Toast.LENGTH_LONG).show();

        }

    };
}

提出课程要求

public class VolleyRequest {
    public static void makeRequest(Context context, String url,
                                   Response.Listener<JSONObject> listenerResponse, Response.ErrorListener listenerError) {

        JsonObjectRequest requestWeather = new JsonObjectRequest(Request.Method.GET, url, null, listenerResponse,
                listenerError);
        Volley.newRequestQueue(context).add(requestWeather);

    }
}
````

java android timertask
1个回答
0
投票

(根据此答案改编:https://stackoverflow.com/a/10156550/2711811]

基本上使用处理程序每​​10秒重新安排一次请求。通过在onStart中创建处理程序,将处理程序附加到主循环程序。

首先,从VolleyRequest.makeRequest中删除onCreate

将成员添加到SecondActivity

private Handler myHandler;
private Runnable myRunnable;

onStartSecondActivity中:

protected void onStart() {
    super.onStart();

    // Start issuing VolleyRequests repeating every 10 seconds.
    myHandler = new Handler();
    myHandler.post(new Runnable() {
        @Override
        public void run() {
            SecondActivity.this.myRunnable = this;
            VolleyRequest.makeRequest(
                SecondActivity.this, 
                URL, 
                SecondActivity.this.listenerResponse, 
                SecondActivity.this.listenerError);
            SecondActivity.this.myHandler.postDelayed(this, 10000);

        }
    };
}

并且在活动停止时停止重复的请求:在onStopSecondActivity中:

protected void onStop() {
    super.onStop();
    myHandler.removeCallbacks(myRunnable);
}
© www.soinside.com 2019 - 2024. All rights reserved.