-1

how to start thread? or when call the sendJson() function so that thread will get started automatically?

One more thing, I would like to start a thread and execute the sendJson() every 5 minutes in background.

public void sendJson(final JSONObject json) {
        Thread t = new Thread() {
            public void run() {
                Log.d(null,"Sync Thread Start");
                Looper.prepare(); //For Preparing Message Pool for the child Thread
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;

                try {
                    HttpPost httpPost = new HttpPost(global.Server + "/BusTicket/sync/sync.php");
                 // Prepare JSON to send by setting the entity
                    httpPost.setEntity(new StringEntity(json.toString(), "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");
                    response = client.execute(httpPost);
                    StatusLine statusLine = response.getStatusLine();
                    String responseString = null;

                    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        response.getEntity().writeTo(out);
                        out.close();
                        responseString = out.toString();
                        Log.d(null,"responseString = "+ responseString  );
                    }
                    /*Checking response */
                    if(response!=null){
                        InputStream in = response.getEntity().getContent(); //Get the data in the entity
                        Log.d(null,"Sync Reponse= "+ convertStreamToString(in));
                        Log.d(null,"Sync Reponse= "+ in.toString() );
                    }

                } catch(Exception e) {
                    e.printStackTrace();
                }

                Looper.loop(); //Loop in the message queue
            }
        };
    }
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
John Walker
  • 1,121
  • 4
  • 26
  • 68

1 Answers1

4

This is just the declaration, to start it, use:

t.start();

More info here. To know how to run your Thread periodically, see this.

Community
  • 1
  • 1
nKn
  • 13,691
  • 9
  • 45
  • 62