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

Running request repeatedly with a timer in Android

我正在寻找与听众一起反复 运行 这个任务的方法。现在,这是可行的,但我正在寻找一种每 10 秒重复一次的方法。

Activity

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

        }

    };
}

Class 提出请求

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

    }
}
````

(改编自此答案:)

基本上使用处理程序每​​ 10 秒重新安排一次请求。处理程序通过在 onStart.

中创建而附加到主循环程序

首先,从 onCreate 中删除 VolleyRequest.makeRequest

将成员添加到 SecondActivity:

private Handler myHandler;
private Runnable myRunnable;

SecondActivityonStart 中:

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

        }
    };
}

并在activity停止时停止重复请求:在SecondActivityonStop中:

protected void onStop() {
    super.onStop();
    // check that it actually ran at least once - can't be null.
    if (myRunnable != null) {
        myHandler.removeCallbacks(myRunnable);
    }
}