要和后台进行通信
一开始发现接不到数据
后来发生了线程错误
在网上查到:在一些高版本中,与网络通信的操作因为要花费比较大的时间,所以应该放在单独的线程中去做。
但为什么一些网上demo没有放在单独的线程中呢?因为那些例子是基于低版本的,低版本不强制要求这么做。
至于线程,因为要改变主UI
用到handler,简单的业务逻辑就是:
0.写好handler的内部操作
1.触发事件
2.进入新的线程
3. 将想返回的信息交给meeage,由handler.sendMessage(message)传回
4.进入handler操作,写入主UI
下面是代码:
public class MainActivity extends ActionBarActivity { Button urlBtn ; TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); urlBtn = (Button)findViewById(R.id.btn1); text=(TextView)findViewById(R.id.textView); urlBtn.setOnClickListener(myClick); } public Handler handler = new Handler(){ public void handleMessage(Message msg){ text.setText(msg.obj.toString()); } }; public View.OnClickListener myClick = new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { urlGet(); } }).start(); } } ; public void setText(){ String a = "123"; Message msg = new Message(); msg.obj = a; // msg.what =1; handler.sendMessage(msg); } public void urlGet(){ String uri = "http://www.haosou.com/?&src=360com"; HttpGet request = new HttpGet(uri); Message msg = new Message(); try{ HttpResponse httpResponse = new DefaultHttpClient().execute(request); if(httpResponse.getStatusLine().getStatusCode()==200){ String result = EntityUtils.toString(httpResponse.getEntity()).trim(); msg.obj= result; handler.sendMessage(msg); } else{ String error = "net has quesetions"; msg.obj = error; handler.sendMessage(msg); } }catch(ClientProtocolException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } } private String readInStream(InputStream in){ Scanner scanner = new Scanner(in).useDelimiter("\\A"); return scanner.hasNext()?scanner.next():""; } }