我试图每隔几秒调用一次api路由(方法)。当前调用路径的方法获取base64字符串,并将字符串作为Image放在我的imageview上。我怎样才能每隔X秒不断调用一次。
目前该方法如下所示:
public void getImageFromApi() {
call = service.getStreamBase64(Utils.getApplicationname(), Utils.getStreamname());
call.enqueue(new retrofit2.Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
Log.e("Tag", response.body().string() + " ");
String result = response.body().string(); // holds the base64 string
byte[] decodedString = Base64.decode(result, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
// Make the imageview visible inside the relative layout, it is GONE inside the xml ...
RelativeLayout drawable = (RelativeLayout) findViewById(R.id.drawable);
drawable.setVisibility(View.VISIBLE);
drawable1.setImageBitmap(decodedByte); // put image on imageview
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (response.code() == 404) {
Toasty.error(VideoChatActivity.this, "Error Code " + response.code() + ": Cannot not access the API!", Toast.LENGTH_SHORT, true).show();
} }
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toasty.error(VideoChatActivity.this, "Error.", Toast.LENGTH_SHORT, true).show();
}
});
}
我需要每隔X秒调用一次,以便图像更新。
答案 0 :(得分:1)
试试这个
声明Timer
全球
Timer timer;
在onCreate()
方法
timer = new Timer();
timer.scheduleAtFixedRate(new RemindTask(), 0, 3000); // delay in seconds
创建一个像这样的新类
private class RemindTask extends TimerTask {
@Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
// call your method here
getImageFromApi();
}
});
}
}
答案 1 :(得分:0)
您可以将android Handler用于此目的
handler.postDelayed(handlerTask, 1000);
在handlerTaskexecuted再次调用之后
答案 2 :(得分:0)
在 onCreate(); 中通过此代码,它将每10秒调用 getImageFromApi()
long SECOND_IN_MILLI = 10000//10 seconds
final Handler timerHandler = new Handler();
final Runnable timerRunnable = new Runnable() {
@Override
public void run() {
getImageFromApi();
timerHandler.postDelayed(this, SECOND_IN_MILLI);
}
};
timerHandler.postDelayed(timerRunnable, SECOND_IN_MILLI);