持续查询服务器以进行常量GET请求的最佳方法是什么?

时间:2018-04-11 03:00:29

标签: android android-volley

这是我的JSON对象

{ 
  "services": [ 
  { 
      "name": "Our Test Service", 
      "authCode": 981846 
  }, 
  { 
      "name": "BuckeyeLink", 
      "authCode": 272860 
  }] 
}

我有网站部分的链接,我想继续做GET请求,询问这些具体信息,但我的问题是最好的方法是什么?

Shoudl我只是做一个不断循环,不断查询服务器?或者有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

无限循环不会有用(永远不会)。你想要的是以一种阶梯式方式(比如每几秒钟)一起使用Handler和Runnable。在您的活动中,您可以将处理程序定义为私有成员,然后将一些方法定义为pollForDatacancelPolling(因为最终,您可能不再对轮询数据更改感兴趣,而您应该取消对设备的电池/性能的友好。)

举个例子,一个简单的活动:

public class YourActivity extends AppCompatActivity {

    private static final String TAG = "YourActivity";
    private long retryInterval = 3000; // 3 seconds
    private Handler handler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.your_layout);
    }

    @Override
    protected void onResume() {
        // when the activity starts, start/resume polling
        super.onResume();
        pollForData();
    }

    @Override
    protected void onPause() {
        // when the activity is paused, also pause the polling
        super.onPause();
        cancelPolling();
    }

    private void pollForData() {
        // I'm a bit heavy on the null checks...

        if(runnable != null) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "Runnable executing");

                    // do the thing that fetches the data
                    getData();

                    // repost this runnable on the interval we defined
                    handler.postDelayed(this, retryInterval);
                }
            };

            // post the first runnable to start the chain
            handler.postDelayed(r, retryInterval);
        }
    }

    private void cancelPolling() {
        // cancel all runnable callbacks for the handler; we're gtg
        if(handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }

    private void getData() {
        // your code to fetch your JSON data from a url
    }
}