永发信息网

安卓开发时在service中创建一个线程,在新线程中通过http访问网络时出现异常,请问如何能正常访问网络?

答案:2  悬赏:80  手机版
解决时间 2021-02-26 23:31
  • 提问者网友:战皆罪
  • 2021-02-26 10:18
如果在主线程中访问网络正常,通过service的新线程访问时就异常,代码如下,异常发生在httpResponse = httpClient.execute(httpGet); 请高手给与解答,重分答谢!

public void run() {
// TODO Auto-generated method stub
String forecastUrl = "http://m.weather.com.cn/data/101070201.html";
//生成一个请求对象
HttpGet httpGet = new HttpGet(forecastUrl);

//生成一个Http客户端对象
HttpClient httpClient = new DefaultHttpClient();
//使用Http客户端发送请求对象
InputStream inputStream = null;
try {
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while((line = reader.readLine()) != null){
result = result + line;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

原来是模拟器问题,已经解决
最佳答案
  • 五星知识达人网友:鸽屿
  • 2021-02-26 10:53
恭喜你!
全部回答
  • 1楼网友:拾荒鲤
  • 2021-02-26 12:03
handlerb当然不能接收到taska中的handlera发送的message,可能有同学会说了,handlera和handlerb都是在主线程中创建的handler,他们都关联于主线程,每个线程都有一个队列messagequeue,looper管理这个队列并且分发消息,无论是handlera还是hand...
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯