2024-09-01
Android/Java
00

android 定时5S更新一次UI,服务器

package com.example.myapplication; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { TextView tv; Button ks; Timer timer = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); ks = (Button) findViewById(R.id.bt); if (null == timer) { timer = new Timer(); } timer.schedule(new TimerTask() { @Override public void run() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .get() .url("http://www.baidu.com") .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Toast.makeText(MainActivity.this, "get failed", Toast.LENGTH_SHORT).show(); } @Override public void onResponse(Call call, final Response response) throws IOException { final String res = response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { tv.setText(res); } }); } }); Log.e("ttt", "ttt"); } }, 5 * 1000, 5 * 1000); } }
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:Dong

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!