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