安卓android多线程开发实例,安卓线程使用例子

我也是刚刚接触程序开发,一个菜鸟。前面和几个同学准备做一个移动教务系统,网上看了很多资料都说了对运行一些费时。如数据库、网络的链接操作,需要新开一个thread对其进行处理。但是后面在对程序进行调试的过程中,刚开始的时候报了空指针错误。根据错误提示,进行修改。说实话,经过那个过程发现自己真的还很菜,排错的经验太少了。直到过了好久才想到报了空指针错误,是因为在线程里生成的对象,因为有时间延迟,对于线程后面的对象来说是空的,所以才导致了空指针错误。后面参考的解决方法是利用join()函数。当然也可用其他方法。

下面写的代码:public class MyThread extends Thread {

private InputStream is = null;

private String url;

private String method;

private List params;

public MyThread(String url, String method, List 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对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值