【问题标题】:Android: How to send http request via service every 10 secondsAndroid:如何通过服务每 10 秒发送一次 http 请求
【发布时间】:2013-10-27 11:38:32
【问题描述】:

我需要每 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);
    }
}
}

非常感谢 视频

【问题讨论】:

    标签: java android service httprequest


    【解决方案1】:

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

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

    10 秒后 doInBackground 将再次执行,之后 onPostExecute 再次执行,handler 再次执行,依此类推……

    【讨论】:

    • 非常感谢您做到了。
    【解决方案2】:

    你可以简单地在android中使用CountDownTimer类。

    public class AlertSessionCountDownTimer extends CountDownTimer {
    
        public AlertSessionCountDownTimer(long startTime, long interval) {
            super(startTime, interval);
        }
    
        @Override
        public void onFinish() {
            //YOUR LOGIC ON FINISH 10 SECONDS
        }
    
        @Override
        public void onTick(long millisUntilFinished) {
            //YOUR LOGIC ON TICK
        }
    }
    

    希望对你有帮助。

    【讨论】:

    • onFinish() 您可以将广播消息发送到任何将调用 Web 服务或执行某些操作并更新数据的类。这取决于您想要如何实现它。 :-)
    【解决方案3】:

    代码只运行一次的原因是你的计时器循环中有一个return。但是,我建议将循环移至后台任务或使用此处给出的其他答案之一,而不是在 onStartCommand() 中实现永远不会返回的循环。

    【讨论】:

      【解决方案4】:
      Handler handler_proc = new Handler();
      
      final Runnable runnable_proc = new Runnable() {
          public void run() {
              requestHttp(new OnFinish() {
                  @Override
                  public void onSuccess() {
                      // pause should be considered since the end of the previous http request.
                      // Otherwise, new requests will occur before the previous one is complete,
                      // if http_timeout > delay
                      handler_proc.postDelayed(runnable_proc, 10000);
                  }
              });
          }
      }
      
      handler_proc.post(runnable_proc);
      

      【讨论】:

        【解决方案5】:

        把返回 START_STICKY; 一段时间后,服务将正常工作

        【讨论】:

        • 您能否更具体地说明这将做什么,以及它将对应用程序产生的影响。
        猜你喜欢
        • 2017-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-22
        • 2012-03-23
        • 2023-04-07
        • 2018-07-12
        • 2021-01-17
        相关资源
        最近更新 更多