Handler作为参数使用的理解

MainActivity

package com.example.tcpsercerandroid;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private EditText mEtContent;
	private TcpManager manager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		manager = TcpManager.getInstance();
		manager.connect(mHandler);
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case TcpManager.STATE_FROM_SERVER_OK:
				String result = (String) msg.obj;
				Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG)
						.show();
				break;

			default:
				break;
			}
		};
	};

	/**
	 * 发送信息
	 * @param view
	 */
	public void clickMessage(View view) {
		mEtContent = (EditText) findViewById(R.id.et);

		if (mEtContent.getText() != null) {
			manager.sendMessage(mEtContent.getText().toString());
		}
	}

	@Override
	protected void onDestroy() {
		manager.disConnect();
		super.onDestroy();
	}

	@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;
	}

}

TcpManager

package com.example.tcpsercerandroid;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Handler;
import android.os.Message;

/**
 * @描述 使用socket实现长连接
 * @项目名称 App_Chat
 * @包名 com.android.chat.utils
 * @类名 TcpUtil
 * @author chenlin
 * @date 2012年6月26日 下午4:06:43
 * @version 1.0
 */
public class TcpManager {
	protected static final int STATE_FROM_SERVER_OK = 0;
	private static String dsName = "192.168.0.103";
	private static int dstPort = 10002;
	private static Socket socket;
	private static TcpManager instance;

	private TcpManager() {
	};

	public static TcpManager getInstance() {
		if (instance == null) {
			synchronized (TcpManager.class) {
				if (instance == null) {
					instance = new TcpManager();
				}
			}
		}
		return instance;
	}

	/**
	 * 连接
	 * 
	 * @return
	 */
	public boolean connect(final Handler handler) {

		if (socket == null || socket.isClosed()) {
			new Thread(new Runnable() {
				@Override
				public void run() {

					try {
						socket = new Socket(dsName, dstPort);
					} catch (UnknownHostException e) {
						e.printStackTrace();
					} catch (IOException e) {
						throw new RuntimeException("连接错误: " + e.getMessage());
					}

					try {
						// 输入流,为了获取客户端发送的数据
						InputStream is = socket.getInputStream();
						byte[] buffer = new byte[1024];
						int len = -1;
						while ((len = is.read(buffer)) != -1) {
							final String result = new String(buffer, 0, len);

							Message msg = Message.obtain();
							msg.obj = result;
							msg.what = STATE_FROM_SERVER_OK;
							handler.sendMessage(msg);
						}
					} catch (IOException e) {
						e.printStackTrace();
					}

				}
			}).start();
		}

		return true;
	}

	/**
	 * 发送信息
	 * 
	 * @param content
	 */
	public void sendMessage(String content) {
		OutputStream os = null;
		try {
			if (socket != null) {
				os = socket.getOutputStream();
				os.write(content.getBytes());
				os.flush();
			}
		} catch (IOException e) {
			throw new RuntimeException("发送失败:" + e.getMessage());
		}
		// 此处不能关闭
		// finally {
		// if (os != null) {
		// try {
		// os.close();
		// } catch (IOException e) {
		// throw new RuntimeException("未正常关闭输出流:" + e.getMessage());
		// }
		// }
		// }
	}

	/**
	 * 关闭连接
	 */
	public void disConnect() {
		if (socket != null && !socket.isClosed()) {
			try {
				socket.close();
			} catch (IOException e) {
				throw new RuntimeException("关闭异常:" + e.getMessage());
			}
			socket = null;
		}
	}
}


handler作为参数传进来,当执行到sendMessage(msg)这里的时候才被使用,然后上图中的handler进行轮询处理



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值