gpt4 book ai didi

java - Android:如何每 10 秒通过服务发送一次 http 请求

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:23:29 24 4
gpt4 key购买 nike

我需要每 10 秒从服务器接收一次状态。

我尝试通过服务发送 http 请求来做到这一点。

问题是我的代码只执行一次。

这是我的服务代码:

public class ServiceStatusUpdate extends Service {

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
while(true)
{
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
new DoBackgroundTask().execute(Utilities.QUERYstatus);
e.printStackTrace();
}
return START_STICKY;
}
}

private class DoBackgroundTask extends AsyncTask<String, String, String> {

@Override
protected String doInBackground(String... params) {
String response = "";
String dataToSend = params[0];
Log.i("FROM STATS SERVICE DoBackgroundTask", dataToSend);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Utilities.AGENT_URL);

try {
httpPost.setEntity(new StringEntity(dataToSend, "UTF-8"));

// Set up the header types needed to properly transfer JSON
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
httpPost.setHeader("Accept-Language", "en-US");

// Execute POST
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if (responseEntity != null) {
response = EntityUtils.toString(responseEntity);
} else {
response = "{\"NO DATA:\"NO DATA\"}";
}
} catch (ClientProtocolException e) {
response = "{\"ERROR\":" + e.getMessage().toString() + "}";
} catch (IOException e) {
response = "{\"ERROR\":" + e.getMessage().toString() + "}";
}
return response;
}

@Override
protected void onPostExecute(String result) {
Utilities.STATUS = result;
Log.i("FROM STATUS SERVICE: STATUS IS:", Utilities.STATUS);
super.onPostExecute(result);
}
}
}

非常感谢视频

最佳答案

在 onPostExecute 中放置一个处理程序以在 10 秒后发送一个 http 请求

new Handler().postDelayed(new Runnable() {
public void run() {
requestHttp();
}
}, 10000);

10 秒后 doInBackground 将再次执行,之后再次执行 onPostExecute,再次处理程序,依此类推。

关于java - Android:如何每 10 秒通过服务发送一次 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19617621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com