安卓线程使用例子
我也是刚刚接触程序开发,一个菜鸟。前面和几个同学准备做一个移动教务系统,网上看了很多资料都说了对运行一些费时。如数据库、网络的链接操作,需要新开一个thread对其进行处理。但是后面在对程序进行调试的过程中,刚开始的时候报了空指针错误。根据错误提示,进行修改。说实话,经过那个过程发现自己真的还很菜,排错的经验太少了。直到过了好久才想到报了空指针错误,是因为在线程里生成的对象,因为有时间延迟,对于线程后面的对象来说是空的,所以才导致了空指针错误。后面参考的解决方法是利用join()函数。当然也可用其他方法。
下面写的代码:
public class MyThread extends Thread { private InputStream is = null; private String url; private String method; private List<NameValuePair> params; public MyThread(String url, String method, List<NameValuePair> params) { this.method = method; this.url = url; this.params = params; } public void run() { try { // check for request method if (method.equals("POST")) { // request method is POST // defaultHttpClient BasicHttpParams httpParameters = new BasicHttpParams(); // Set the default socket timeout (SO_TIMEOUT) HttpConnectionParams .setConnectionTimeout(httpParameters, 30000); // in milliseconds which is the timeout for waiting for // data. HttpConnectionParams.setSoTimeout(httpParameters, 30000); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); setIs(httpEntity.getContent()); } else if (method.equals("GET")) { BasicHttpParams httpParameters = new BasicHttpParams(); // Set the default socket timeout (SO_TIMEOUT) HttpConnectionParams .setConnectionTimeout(httpParameters, 30000); // in milliseconds which is the timeout for waiting for // data. HttpConnectionParams.setSoTimeout(httpParameters, 30000); // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); String temp_url = url + "?" + paramString; HttpGet httpGet = new HttpGet(temp_url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); setIs(httpEntity.getContent()); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public InputStream getIs() { return is; } public void setIs(InputStream is) { this.is = is; } }
通过下面的语句对以上生成的对象(“setIs(httpEntity.getContent());
“)进行调用
MyThread myThread = new MyThread(url, method, params); myThread.start(); myThread.join();//同做join()函数对myThread进行处理,使其一般的对象那样使用即可 is = myThread.getIs();//获得is对象
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。