Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> ANDROID HttpURLConnection,HttpClient和最簡單的handler機制

ANDROID HttpURLConnection,HttpClient和最簡單的handler機制

編輯:關於Android編程

handler機制在Android開發中主要用於主線程和子線程的溝通,子線程發送必要的信息給主線程,然後在主線程中更新ui;

 

package com.example.webview;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements OnClickListener{
	
	public static final int SHOW_RESPONSE=0;
	private TextView reponseText;
	private Button sendButton;
	
	private Handler handler=new Handler(){

		/* (non-Javadoc)
		 * @see android.os.Handler#handleMessage(android.os.Message)
		 */
		@Override
		public void handleMessage(Message msg) {
//			接收消息並且去更新UI線程上的控件內容
			switch (msg.what) {
			case SHOW_RESPONSE:
				String response=(String) msg.obj;
				reponseText.setText(response);
				break;
			default:
				Toast.makeText(MainActivity.this, show fail!!, Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		sendButton=(Button) findViewById(R.id.send_request_id);
		reponseText=(TextView) findViewById(R.id.text_id);
		sendButton.setOnClickListener(this);
		
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		sendRequestWithHttpURLConnection();
		Toast.makeText(MainActivity.this, onclick!1, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 開啟線程來發起網路請求
	 */
	private void sendRequestWithHttpURLConnection() {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				HttpURLConnection connection=null;
				try {
					URL url=new URL(http://www.baidu.com);
					connection=(HttpURLConnection) url.openConnection();
					connection.setRequestMethod(GET);
//					設置連接超時
					connection.setConnectTimeout(8000);
//					設置讀取超時
					connection.setReadTimeout(8000);
//					獲取輸入流,進行讀取
					InputStream inputStream=connection.getInputStream();
					BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
//					下面這個StringBuilder 的作用相當於一個String
					StringBuilder response=new StringBuilder();
					while (reader.readLine()!=null) {
//						讀一行就,把讀到的添加到response裡面
						response.append(reader.readLine());
					}
//					調用dandler的obtainmessage方法,得到一個message對象
					Message message=handler.obtainMessage();
/*					一個message對象,public static Message obtain(Handler h, int what, int arg1, int arg2, Object obj),
					h:處理消息的目標Handler對象;
					what:消息的編碼;
					arg1:附加的整數數據;
					arg2:附加的整數數據;
					obj:附件的Object類型數據。
					返回值:從全局的對象池中返回一個Message對象。*/
					message.what=SHOW_RESPONSE;
					message.obj=response.toString();
//					這裡是子線程,這個用handler發送信息給主線程
					handler.sendMessage(message);
					
				} catch (Exception e) {
					// TODO: handle exception
				}finally{
					connection.disconnect();
				}
			}
		}).start();
		
		Toast.makeText(MainActivity.this, thread start, Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved