2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Android]作ったHttpClientを利用してポーリングクラスを作ってみた

Last updated at Posted at 2015-10-02

[Android]AndroidHttpClientがNGになっていたので、HttpURLConnectionでアクセスしてみた

上記で作成したHttpクライアントを利用して、
ポーリングクラスを作成しました。
プッシュ通信などがある昨今で今更なクラスですが。。。

今回はRxAndroidおよびRetrolambdaを利用してコードを書いているので注意してください。

HttpPollingClient.java
    private HttpClient client = new HttpClient();
    private String url = "";
    private Action1<String> action = param1 -> {};

    public HttpPollingClient(String url, Action1<String> event){
        this.url = url;
        this.action = event;
    }

    private Thread thread = null;
    private boolean isPlay = false;
    public void start(long waitTime) {
        isPlay = true;
        thread = new Thread(() -> {
            while (isPlay){
                exe();
                try{
                    Thread.sleep(waitTime);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    public void exe(){
        String pageData = client.get(url);
        action.call(pageData);
    }

    public void stop(){
        new Thread(() -> {
            stopSync();
        }).start();
    }

    public void stopSync(){
        isPlay = false;
        if (thread == null){
            return;
        }
        
        while (thread.isAlive()){
            try{
                Thread.sleep(waitTime);
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

コンストラクタを作成する際に、ページの取得後に動作させるイベントを登録してください。

//使い方
HttpPollingClient client = new HttpPollingClient("http://localhost:8080/index.html", HttpPollingClient("", (page) -> Log.i("TAG", page)));

// ポーリング開始
client.start();
.
.
.
// ポーリング停止
client.stop();
// 停止の同期をとりたい場合
client.stopSync();
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?