簡體   English   中英

Android我可以知道如何啟動線程嗎?

[英]Android May i know how to start the thread?

如何啟動線程? 還是在調用sendJson()函數時使線程自動啟動?

還有一件事,我想啟動一個線程並在后台每5分鍾執行一次sendJson()

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
            }
        };
    }

這只是聲明,要開始使用,請使用:

t.start();

更多信息在這里 要了解如何定期運行您的Thread ,請參閱this

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM