【问题标题】:HttpPost response every 5 second每 5 秒 HttpPost 响应
【发布时间】:2013-09-10 19:33:48
【问题描述】:

我正在尝试从服务器读取一个变量以每 5 秒对其进行一次评估,然后发送另一个变量,但我无法转换此代码来实现它。并尝试使用计时器,但这不起作用,我对 SoTimeout 的理解不够好,无法以这种方式使用它[。]我希望接收到的变量只能通过某种条件进行评估。 [我] 在这个 httppost 中很新

private void EnviarDatos(int var){


    HttpClient httpclient = new DefaultHttpClient();   
    HttpPost httppost = new HttpPost("http://www.******.com/leo/app2.php");

    try {               
    List<NameValuePair> postValues = new ArrayList<NameValuePair>(2);         
    postValues.add(new BasicNameValuePair("a", Integer . toString ( var )));                 
    httppost.setEntity(new UrlEncodedFormEntity(postValues));          
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();    
    String res= StreamToString(is);
    int entero = Integer.parseInt(res);


    Message sms = new Message();
    sms.obj = res;
    bridge.sendMessage(sms);
}catch (IOException e) {         
    //TODO Auto-generated catch block     
 } 
}


public String StreamToString(InputStream is) {

    BufferedReader reader = 
        new BufferedReader(new InputStreamReader(is));
   StringBuilder sb = new StringBuilder();
 String line = null;
 try {
 while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
 }
 } catch (IOException e) {
     e.printStackTrace();
 } finally {
    try {
    is.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
 }
return sb.toString();
}



private Handler bridge = new Handler() {
 @Override

 Toast.makeText(getApplicationContext(), (String)msg.obj, 
   Toast.LENGTH_LONG).show();
 }
};

【问题讨论】:

  • 你需要用英文重写你的问题。

标签: java android timeout http-post


【解决方案1】:

setSoTimeout 用于指定要等待服务器响应的时间,因此可以将其设置为等待 10 秒,之后将继续该过程,我建议您为此任务创建一个服务.这是一个非常完整的教程:http://www.vogella.com/articles/AndroidServices/article.html

试试这个:

mTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
       // What you want to do goes here
     }
}, 0, REFRESH_TIME);

您的问题有多种解决方案: How to always run a service in the background?

Android run thread in service every X seconds

How to start Service using Alarm Manager in Android?

【讨论】:

  • 它有效,但如果您第一次发送正常但连续循环出错
猜你喜欢
  • 1970-01-01
  • 2022-01-09
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多