[英]Android Studio - Java - API
我正在使用OkHttpClient連接到API。
Request request = new Request.Builder()
.url(BPI_ENDPOINT)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(Test.this, "Error during BPI loading : "
+ e.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response)
throws IOException {
final String body = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
parseBpiResponse(body);
}
});
}
});
parseBpiResponse
只是在TextView
顯示數據,但是來自站點的數據請求僅發生一次,為了再次獲取數據,我需要重新激活活動或實現按鈕或滑動屏幕等,
如何不斷調用API請求,以使數據保持更新,而不是通過用戶輸入來進行?
您可以使用Timer類定期進行網絡調用
final long period = 0;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// do your task here
}
}, 0, period);
使用此代碼,但您應注意此代碼中的活動和視圖,這會導致令人討厭的異常和內存泄漏,更好的方法是將實時數據與遞歸函數一起使用!
new Thread(new Runnable() {
@Override
public void run() {
//Checks the life cycle of the activity and if activity was destroyed break the while loop and exits
while (true && getLifecycle().getCurrentState() != Lifecycle.State.DESTROYED) {
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(Test.this, "Error during BPI loading : "
+ e.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response)
throws IOException {
final String body = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
if (getLifecycle().getCurrentState() != Lifecycle.State.DESTROYED)
parseBpiResponse(body);
}
});
}
});
try {
//Waits for 1 sec
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
只需進行遞歸調用即可,例如:
public void callAPI()
{
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(Test.this, "Error during BPI loading : "
+ e.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response)
throws IOException {
final String body = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
parseBpiResponse(body);
}
});
**//just use handler/timer or thread to post event after some interval**
new android.os.Handler().postDelayed(new Runnable() {
@Override
public void run() {
callAPI();
}
},2000);
}
});
}
我也建議將Rxjava+Retrofit
與OkHttp
使用,並使用interval
函數使其變得更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.