繁体   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