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

我需要每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,再次处理程序,依此类推。

以上是 Android:如何每10秒通过服务发送一次HTTP请求 的全部内容, 来源链接: utcz.com/qa/427862.html

回到顶部