1. 程式人生 > >handler、HttpURLConnection、網路資料下載綜合使用。

handler、HttpURLConnection、網路資料下載綜合使用。

1. Google在設計的framework的時候禁止開發者在非UI執行緒去更新介面UI。

2.handler主要是在主執行緒中接受子執行緒傳送的資料,並根據此資料來更新UI,android提供了handler作為主執行緒和子執行緒的紐帶;

 3.Message也可以指定並傳遞資料,message共有幾個主要的屬性what,object,arg1,arg2.

package com.example.handlertest;

import java.util.ArrayList;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView textview;
private Handler handler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textview=(TextView) findViewById(R.id.test);
		new Thread(today).start();
		handler=new Handler(){
			public void handleMessage(android.os.Message msg) {
				System.out.println(msg+"-----");
				String str="";
				for(String temp:(ArrayList<String>)msg.obj){
					str+=temp;
					textview.setText(msg.what+str);
				}
							
			};
		};
//		handler.handleMessage(Message msg);
	}

	Runnable today=new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				Thread.sleep(2000);
				Message message=Message.obtain();
				message.what=1;
				message.arg1=100;
				message.arg2=200;
				ArrayList<String> str=new ArrayList<String>();
				str.add("給自己的情書");
				str.add("你快樂所以我快le");
				message.obj=str;
				handler.sendMessage(message);
				
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	};

}
 

handler,網路請求的綜合使用

eg:訪問百度獲取資料並更改UI。

MainActivity.ava


package com.example.handlertest;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textview;
private URL url;
private HttpURLConnection conn;
private Handler handler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textview=(TextView) findViewById(R.id.test);
	    new Thread(networkTask).start();
		handler=new Handler(){
			public void handleMessage(Message msg) {
				String temp=msg.getData().toString();				
				textview.setText(temp);
			};
		};
	}
	Runnable networkTask = new Runnable() {
		public void run() {
			
			String a="https://www.baidu.com/";
			 StringBuilder sb = null;
	            InputStream is = null;
	            try {	               
	                url = new URL(a);
	                conn = (HttpURLConnection) url.openConnection();
	                conn.setRequestMethod("GET");
	                conn.setConnectTimeout(5000);
	                conn.setReadTimeout(5000);
	                conn.setDoInput(true);	            
	                conn.connect();	             	                
	                char[] buffer = new char[1024];
	                if(conn.getResponseCode() == 200){
	                    is = conn.getInputStream();
	                    InputStreamReader isr = new InputStreamReader(is,"UTF-8");
	                    int count = 0;
	                    sb = new StringBuilder();
	                    while ((count = isr.read(buffer, 0, buffer.length)) != -1) {	                       
	                        sb.append(new String(buffer, 0, count));
	                    }
	                    Log.i("TAG",sb.toString());
	                   
	                }
	            } catch (MalformedURLException e) {
	                e.printStackTrace();
	            } catch (ProtocolException e) {
	                e.printStackTrace();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
			Message message = Message.obtain();
		//	message.obj=sb.toString();
			Bundle data = new Bundle();
			data.putString("value", sb.toString());
			message.setData(data);
			handler.sendMessage(message);
		};
	};

}




三、帶json解析的綜合使用

             待待待......