-2

I'm trying to read a variable from a server to evaluate it every 5 seconds and then send another variable but I am not able to convert this code to make that. And tried with a timer, but that does not work and I do not understand the SoTimeout well enough to use it in that way[.] I want the variable that is received to only be evaluated by some condition. [I] am very new in this 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();
 }
};

1 Answers1

0

The setSoTimeout is used to specify how long you want to wait for the response from the server, so you can put it waits 10 seconds and after that time will continue with the process, I recommend that you create a service for this task. This is a very complete tutorial: http://www.vogella.com/articles/AndroidServices/article.html

Try this:

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

There are several solutions for your issue: 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?

Community
  • 1
  • 1
Tobiel
  • 1,543
  • 12
  • 19