CSS 特性选择器

[IMG_1095

ref:《HTML & CSS设计与构建网站》 p.281

RTSP客户端测试(Java)

IRTSPEvent.java

public interface IRTSPEvent {
	void connect() throws IOException;

	void read(SelectionKey key) throws IOException;

	void write() throws IOException;
}

RTSPClient.java

public class RTSPClient extends Thread implements IRTSPEvent {

	private static final String VERSION = " RTSP/1.0\r\n";
	private static final String RTSP_OK = "RTSP/1.0 200 OK";

	private final InetSocketAddress remoteAddress;

	private SocketChannel socketChannel;

	private final ByteBuffer sendBuf;
	private final ByteBuffer receiveBuf;
	private static final int BUFFER_SIZE = 8192;

	private Selector selector;
	private String rtspAddress;
	private Status sysStatus;
	private String sessionId;
	private String trackInfo;

	private AtomicBoolean shutdown;
	private int seq = 1;
	private boolean isSent;

	private enum Status {
		init, options, describe, setup, play, pause, teardown, error, exit
	}

	public RTSPClient(InetSocketAddress remoteAddress, String rtspAddress) {
		this.remoteAddress = remoteAddress;
		this.rtspAddress = rtspAddress;

		sendBuf = ByteBuffer.allocateDirect(BUFFER_SIZE);
		receiveBuf = ByteBuffer.allocateDirect(BUFFER_SIZE);

		if (selector == null) {
			try {
				selector = Selector.open();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		sysStatus = Status.init;
		shutdown = new AtomicBoolean(false);
		isSent = false;
		
		startup();
	}

	public void startup() {
		try {
			socketChannel = SocketChannel.open();
			socketChannel.socket().setSoTimeout(5 * 60 * 1000);
			socketChannel.configureBlocking(false);
			socketChannel.connect(remoteAddress);
			socketChannel.register(selector, SelectionKey.OP_CONNECT
					| SelectionKey.OP_READ | SelectionKey.OP_WRITE, this);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void send(byte[] out) {
		if (out == null || out.length < 1) {
			return;
		}

		synchronized (sendBuf) {
			sendBuf.clear();
			sendBuf.put(out);
			sendBuf.flip();
		}

		try {
			write();
			isSent = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean isConnected() {
		return socketChannel != null && socketChannel.isConnected();
	}

	public byte[] receive() {
		if (isConnected()) {
			try {
				int len = 0;
				int readBytes = 0;

				synchronized (receiveBuf) {
					receiveBuf.clear();
					try {
						while ((len = socketChannel.read(receiveBuf)) > 0) {
							readBytes += len;
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						receiveBuf.flip();
					}
					if (readBytes > 0) {
						final byte[] tmp = new byte[readBytes];
						receiveBuf.get(tmp);
						return tmp;
					} else {
						System.err.println("Receive empty data from server");
						return null;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			System.err.println("Client not Connected");
		}
		return null;
	}

	private void select() {
		int n = 0;

		try {
			if (selector == null) {
				return;
			}
			Thread.sleep(1000);
			n = selector.select(1000);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (n > 0) {
			final Iterator<SelectionKey> iter = selector.selectedKeys()
					.iterator();
			while (iter.hasNext()) {
				final SelectionKey sk = iter.next();

				iter.remove();
				if (!sk.isValid()) {
					continue;
				}

				final IRTSPEvent handler = (IRTSPEvent) sk.attachment();
				try {
					if (sk.isConnectable()) {
						handler.connect();
					} else if (sk.isReadable()) {
						handler.read(sk);
					}
				} catch (IOException e) {
					e.printStackTrace();
					sk.cancel();
				}

			}

		}
	}

	public void shutdown() {
		if (isConnected()) {
			try {
				socketChannel.close();
				System.out.println("Client Shutdown");
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				socketChannel = null;
			}
		} else {
			System.err.println("Client not connected");
		}
	}

	@Override
	public void run() {
		while (!shutdown.get()) {
			try {
				if (isConnected() && (!isSent)) {
					switch (sysStatus) {
					case init:
						OptionCmd();
						break;
					case options:
						DescribeCmd();
						break;
					case describe:
						SetupCmd();
						break;
					case setup:
						PlayCmd();
						break;
					case play:
						PauseCmd();
						break;
					case pause:
						TeardownCmd();
						break;
					case teardown:
						shutdown.set(true);
						break;
					case error:
						System.err.println("Something error, Client will shutdown ...");
						shutdown.set(true);
					default:
						break;
					}
				}

				if (!shutdown.get()) {
					select();
				}

				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		shutdown();
	}

	public void handle(byte[] msg) {
		String tmp = new String(msg);
		System.out.println("Server >>>>\n" + tmp);

		if (tmp.startsWith(RTSP_OK)) {
			switch (sysStatus) {
			case init:
				sysStatus = Status.options;
				break;
			case options:
				trackInfo = tmp.substring(tmp.indexOf("trackID"));
				if (trackInfo != null || trackInfo.length() > 0) {
					sysStatus = Status.describe;
				} else {
					sysStatus = Status.error;
				}
				break;
			case describe:
				sessionId = tmp.substring(tmp.indexOf("Session: ") + 9,
						tmp.indexOf(";"));
				if (sessionId != null && sessionId.length() > 0) {
					sysStatus = Status.setup;
				} else {
					sysStatus = Status.error;
					System.err.println("SessionId error");
				}
				break;
			case setup:
				sysStatus = Status.play;
				break;
			case play:
				sysStatus = Status.pause;
				break;
			case pause:
				sysStatus = Status.teardown;
				break;
			case teardown:
				sysStatus = Status.exit;
			default:
				break;
			}
			isSent = false;
		} else {
			sysStatus = Status.error;
			System.err.println("Server error: " + tmp);
		}
	}

	@Override
	public void connect() throws IOException {
		if (isConnected()) {
			return;
		}

		do {
			socketChannel.finishConnect();
			if (!socketChannel.isConnected()) {
				try {
					Thread.sleep(1 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} while (!socketChannel.isConnected());
	}


	@Override
	public void read(SelectionKey key) throws IOException {
		final byte[] msg = receive();
		if (msg != null) {
			handle(msg);
		} else {
			key.cancel();
		}
	}

	@Override
	public void write() throws IOException {
		if (isConnected()) {
			try {
				socketChannel.write(sendBuf);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.err.println("Client not connected");
		}
	}
	
	private void TeardownCmd() {
		StringBuilder sb = new StringBuilder();
		sb.append("TEARDOWN ");
		sb.append(this.rtspAddress);
		sb.append(VERSION);
		sb.append("Cseq: ");
		sb.append(seq++);
		sb.append("\r\n");
		sb.append("User-Agent: VLC\r\n");
		sb.append("Session: ");
		sb.append(sessionId);
		sb.append("\r\n");
		sb.append("\r\n");
		System.out.println("Client >>>>\n" + sb.toString());
		send(sb.toString().getBytes());
	}

	private void PlayCmd() {
		StringBuilder sb = new StringBuilder();
		sb.append("PLAY ");
		sb.append(this.rtspAddress);
		sb.append(VERSION);
		sb.append("Session: ");
		sb.append(sessionId);
		sb.append("\r\n");
		sb.append("Cseq: ");
		sb.append(seq++);
		sb.append("\r\n");
		sb.append("\r\n");
		System.out.println("Client >>>>\n" + sb.toString());
		send(sb.toString().getBytes());
	}

	private void SetupCmd() {
		StringBuilder sb = new StringBuilder();
		sb.append("SETUP ");
		sb.append(this.rtspAddress);
		sb.append("/");
		sb.append(trackInfo);
		sb.append(VERSION);
		sb.append("Cseq: ");
		sb.append(seq++);
		sb.append("\r\n");
		sb.append("Transport: RTP/AVP;UNICAST;client_port=16264-16265;mode=play\r\n");
		sb.append("\r\n");
		System.out.println("Client >>>>\n" + sb.toString());
		send(sb.toString().getBytes());
	}

	private void OptionCmd() {
		StringBuilder sb = new StringBuilder();
		sb.append("OPTIONS ");
		sb.append(this.rtspAddress.substring(0,
				this.rtspAddress.lastIndexOf("/")));
		sb.append(VERSION);
		sb.append("Cseq: ");
		sb.append(seq++);
		sb.append("\r\n");
		sb.append("\r\n");
		System.out.println("Client >>>>\n" + sb.toString());
		send(sb.toString().getBytes());
	}

	private void DescribeCmd() {
		StringBuilder sb = new StringBuilder();
		sb.append("DESCRIBE ");
		sb.append(this.rtspAddress);
		sb.append(VERSION);
		sb.append("Cseq: ");
		sb.append(seq++);
		sb.append("\r\n");
		sb.append("\r\n");
		System.out.println("Client >>>>\n" + sb.toString());
		send(sb.toString().getBytes());
	}

	private void PauseCmd() {
		StringBuilder sb = new StringBuilder();
		sb.append("PAUSE ");
		sb.append(this.rtspAddress);
		sb.append("/");
		sb.append(VERSION);
		sb.append("Cseq: ");
		sb.append(seq++);
		sb.append("\r\n");
		sb.append("Session: ");
		sb.append(sessionId);
		sb.append("\r\n");
		sb.append("\r\n");
		System.out.println("Client >>>>\n" + sb.toString());
		send(sb.toString().getBytes());
	}

	public static void main(String[] args) {
		try {
			RTSPClient client = new RTSPClient(new InetSocketAddress(
					"192.168.2.191", 554),
					"rtsp://192.168.2.191:554/user=admin&password=admin&channel=1&stream=0.sdp");
			client.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

github: https://github.com/lnmcc/testRTSP.git

RTSP命令的解释点击 这里

一些关于流媒体的基本概念点击 这里

RTSP交互命令简介及过程参数描述(转)

Real Time Streaming Protocol或者RTSP(实时流媒体协议),是由Real network 和 Netscape共同提出的如何有效地在IP网络上传输流媒体数据的应用层协议。RTSP提供一 种可扩展的框架,使能够提供可控制的,按需传输实时数据,比如音频和视频文件。源数据可以包括现场数据的反馈和存贮的文件。rtsp对流媒体提供了诸如暂停,快进等控制,而它本身并不传输数据,rtsp作用相当于流媒体服务器的远程控制。传输数据可以通过传输层的tcp,udp协议,rtsp也提供了基于rtp传输机制的一些有效的方法。

RTSP消息格式

RTSP的消息有两大类,一是请求消息(request),一是回应消息(response),两种消息的格式不同. 请求消息:

方法 URI RTSP版本 CR LF 
消息头 CR LF CR LF 
消息体 CR LF 

其中方法包括OPTION回应中所有的命令,URI是接受方的地址,例如 rtsp://192.168.20.136 RTSP版本一般都是 RTSP/1.0.每行后面的CR LF表示回车换行,需要接受端有相应的解析,最后一个消息头需要有两个CR LF 回应消息:

RTSP版本 状态码 解释 CR LF 
消息头 CR LF CR LF 
消息体 CR LF

其中RTSP版本一般都是RTSP/1.0,状态码是一个数值,200表示成功,解释是与状态码对应 的文本解释。

简单的rtsp交互过程

C表示rtsp客户端,S表示rtsp服务端

1.C->S:OPTION request //询问S有哪些方法可用 
1.S->C:OPTION response //S回应信息中包括提供的所有可用方法 

2.C->S:DESCRIBE request //要求得到S提供的媒体初始化描述信息 
2.S->C:DESCRIBE response //S回应媒体初始化描述信息,主要是sdp 

3.C->S:SETUP request //设置会话的属性,以及传输模式,提醒S建立会话 
3.S->C:SETUP response //S建立会话,返回会话标识符,以及会话相关信息 

4.C->S:PLAY request //C请求播放 
4.S->C:PLAY response //S回应该请求的信息 

5.S->C:发送流媒体数据 

6.C->S:TEARDOWN request //C请求关闭会话 
6.S->C:TEARDOWN response //S回应该请求 

上述的过程是标准的、友好的rtsp流程,但实际的需求中并不一定按部就班来。 其中第3和4步是必需的! 第一步,只要服务器客户端约定好,有哪些方法可用,则option请求可以不要。第二步,如果我们有其他途径得到媒体初始化描述信息(比如http请求等等),则我们也不需要通过rtsp中的describe请求来完成。第五步,可以根据系统需求的设计来决定是否需要。

rtsp中常用方法

OPTION

目的是得到服务器提供的可用方法:

OPTIONS rtsp://192.168.20.136:5000/xxx666 RTSP/1.0 
CSeq: 1 //每个消息都有序号来标记,第一个包通常是option请求消息 
User-Agent: VLC media player (LIVE555 Streaming Media v2005.11.10) 

服务器的回应信息包括提供的一些方法,例如:

RTSP/1.0 200 OK 
Server: UServer 0.9.7_rc1 
Cseq: 1 //每个回应消息的cseq数值和请求消息的cseq相对应 
Public: OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE, SCALE, 
GET_PARAMETER //服务器提供的可用的方法 

DESCRIBE

C向S发起DESCRIBE请求,为了得到会话描述信息(SDP):

DESCRIBE rtsp://192.168.20.136:5000/xxx666 RTSP/1.0 

CSeq: 2 
token: 
Accept: application/sdp 
User-Agent: VLC media player (LIVE555 Streaming Media v2005.11.10) 

服务器回应一些对此会话的描述信息(sdp):

RTSP/1.0 200 OK 
Server: UServer 0.9.7_rc1 
Cseq: 2 
x-prev-url: rtsp://192.168.20.136:5000 
x-next-url: rtsp://192.168.20.136:5000 
x-Accept-Retransmit: our-retransmit 
x-Accept-Dynamic-Rate: 1 
Cache-Control: must-revalidate 
Last-Modified: Fri, 10 Nov 2006 12:34:38 GMT 
Date: Fri, 10 Nov 2006 12:34:38 GMT 
Expires: Fri, 10 Nov 2006 12:34:38 GMT 
Content-Base: rtsp://192.168.20.136:5000/xxx666/ 
Content-Length: 344 
Content-Type: application/sdp 

v=0 //以下都是sdp信息 
o=OnewaveUServerNG 1451516402 1025358037 IN IP4 192.168.20.136 
s=/xxx666 
u=http:/// 
[email protected] 
c=IN IP4 0.0.0.0 
t=0 0 
a=isma-compliance:1,1.0,1 

a=range:npt=0- 
m=video 0 RTP/AVP 96 //m表示媒体描述,下面是对会话中视频通道的媒体描述 
a=rtpmap:96 MP4V-ES/90000 
a=fmtp:96 
profile-level-id=245;config=000001B0F5000001B509000001000000012000C888B0E0E0FA62D089028307 

a=control:trackID=0//trackID=0表示视频流用的是通道0 

SETUP

客户端提醒服务器建立会话,并确定传输模式:

SETUP rtsp://192.168.20.136:5000/xxx666/trackID=0 RTSP/1.0 
CSeq: 3 
Transport: RTP/AVP/TCP;unicast;interleaved=0-1 
User-Agent: VLC media player (LIVE555 Streaming Media v2005.11.10) 

uri中带有trackID=0,表示对该通道进行设置。Transport参数设置了传输模式,包 的结构。接下来的数据包头部第二个字节位置就是interleaved,它的值是每个通道都 不同的,trackID=0的interleaved值有两个0或1,0表示rtp包,1表示rtcp包,接受端 根据interleaved的值来区别是哪种数据包。

服务器回应信息:

RTSP/1.0 200 OK 
Server: UServer 0.9.7_rc1 
Cseq: 3 
Session: 6310936469860791894 //服务器回应的会话标识符 
Cache-Control: no-cache 
Transport: RTP/AVP/TCP;unicast;interleaved=0-1;ssrc=6B8B4567 

PLAY

客户端发送播放请求:

PLAY rtsp://192.168.20.136:5000/xxx666 RTSP/1.0 
CSeq: 4 
Session: 6310936469860791894 
Range: npt=0.000- //设置播放时间的范围 
User-Agent: VLC media player (LIVE555 Streaming Media v2005.11.10) 

服务器回应信息:

RTSP/1.0 200 OK 
Server: UServer 0.9.7_rc1 
Cseq: 4 
Session: 6310936469860791894 
Range: npt=0.000000- 
RTP-Info: url=trackID=0;seq=17040;rtptime=1467265309 
//seq和rtptime都是rtp包中的信息 

PAUSE

客户端发起暂停请求:

PAUSE rtsp://192.168.20.136:5000/xxx666 RTSP/1.0 
Cseq: 5
Session: 6310936469860791894

服务器回应:

RTSP/1.0 200 OK 
Server: UServer 0.9.7_rc1 
Cseq: 5 
Session: 6310936469860791894

TEARDOWN

客户端发起关闭请求:

TEARDOWN rtsp://192.168.20.136:5000/xxx666 RTSP/1.0 
CSeq: 6
Session: 6310936469860791894 
User-Agent: VLC media player (LIVE555 Streaming Media v2005.11.10) 

服务器回应:

RTSP/1.0 200 OK 
Server: UServer 0.9.7_rc1 
Cseq: 6
Session: 6310936469860791894 
Connection: Close 

其他方法

以上方法都是交互过程中最为常用的,其它还有一些重要的方法如: get/set_parameter,pause,redirect等等

sdp的格式

v=<version> 
o=<username> <session id> <version> <network type> <address type> <address> 
s=<session name> 
i=<session description> 
u=<URI> 
e=<email address> 
p=<phone number> 
c=<network type> <address type> <connection address> 
b=<modifier>:<bandwidth-value> 
t=<start time> <stop time> 
r=<repeat interval> <active duration> <list of offsets from start-time> 
z=<adjustment time> <offset> <adjustment time> <offset> .... 
k=<method> 
k=<method>:<encryption key> 
a=<attribute> 
a=<attribute>:<value> 
m=<media> <port> <transport> <fmt list> 
v = (协议版本) 
o = (所有者/创建者和会话标识符) 
s = (会话名称) 
i = * (会话信息) 
u = * (URI 描述) 
e = * (Email 地址) 
p = * (电话号码) 
c = * (连接信息) 
b = * (带宽信息) 
z = * (时间区域调整) 
k = * (加密密钥) 
a = * (0 个或多个会话属性行) 
时间描述: 
t = (会话活动时间) 
r = * (0或多次重复次数) 
媒体描述: 
m = (媒体名称和传输地址) 
i = * (媒体标题) 
c = * (连接信息 — 如果包含在会话层则该字段可选) 
b = * (带宽信息) 
k = * (加密密钥) 
a = * (0 个或多个媒体属性行) 

RTSP点播消息流程实例

客户端:VLC RTSP服务器:LIVE555 Media Server

1)C(Client)-> M(Media Server) 
OPTIONS rtsp://192.168.1.109/1.mpg RTSP/1.0 
CSeq: 1 
user-Agent: VLC media player(LIVE555 Streaming Media v2007.02.20) 

1)M -> C 
RTSP/1.0 200 OK 
CSeq: 1 
Date: wed, Feb 20 2008 07:13:24 GMT 
Public: OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE 

2)C -> M 
DESCRIBE rtsp://192.168.1.109/1.mpg RTSP/1.0 
CSeq: 2 
Accept: application/sdp 
User-Agent: VLC media player(LIVE555 Streaming Media v2007.02.20) 

2)M -> C 
RTSP/1.0 200 OK 
CSeq: 2 
Date: wed, Feb 20 2008 07:13:25 GMT 
Content-Base: rtsp://192.168.1.109/1.mpg/ 
Content-type: application/sdp 
Content-length: 447 
v=0 
o =- 2284269756 1 IN IP4 192.168.1.109 
s=MPEG-1 or 2 program Stream, streamed by the LIVE555 Media Server 
i=1.mpg 
t=0 0 
a=tool:LIVE555 Streaming Media v2008.02.08 
a=type:broadcast 
a=control:* 
a=range:npt=0-66.181 
a=x-qt-text-nam:MPEG-1 or Program Stream, streamed by the LIVE555 Media Server 
a=x-qt-text-inf:1.mpg 
m=video 0 RTP/AVP 32 
c=IN IP4 0.0.0.0 
a=control:track1 
m=audio 0 RTP/AVP 14 
c=IN IP4 0.0.0.0 
a=control:track2 

3)C -> M 
SETUP rtsp://192.168.1.109/1.mpg/track1 RTSP/1.0 
CSeq: 3 
Transport: RTP/AVP; unicast;client_port=1112-1113 
User-Agent: VLC media player(LIVE555 Streaming Media v2007.02.20) 

3)M -> C 
RTSP/1.0 200 OK 
CSeq: 3 
Date: wed, Feb 20 2008 07:13:25 GMT 
Transport: RTP/AVP;unicast;destination=192.168.1.222;source=192.168.1.109;client_port=1112-1113;server_port=6970-6971 
Session: 3 

4)C -> M 
SETUP rtsp://192.168.1.109/1.mpg/track2 RTSP/1.0 
CSeq: 4 
Transport: RTP/AVP; unicast;client_port=1114-1115 
Session: 3 
User-Agent: VLC media player(LIVE555 Streaming Media v2007.02.20) 

4)M -> C 
RTSP/1.0 200 OK 
CSeq: 4 
Date: wed, Feb 20 2008 07:13:25 GMT 
Transport: RTP/AVP;unicast;destination=192.168.1.222;source=192.168.1.109;client_port=1114-1115;server_port=6972-6973 
Session: 3 

5)C -> M 
PLAY rtsp://192.168.1.109/1.mpg/ RTSP/1.0 
CSeq: 5 
Session: 3 
Range: npt=0.000- 
User-Agent: VLC media player(LIVE555 Streaming Media v2007.02.20) 

5)M -> C 
RTSP/1.0 200 OK 
CSeq: 5 
Range: npt=0.000- 
Session: 3 
RTP-Info: url=rtsp://192.168.1.109/1.mpg/track1;seq=9200;rtptime=214793785,url=rtsp://192.168.1.109/1.mpg/track2;seq=12770;rtptime=31721

(开始传输流媒体…)

ref: http://blog.csdn.net/DiegoTJ/article/details/5541877

CSS 常用选择器类型

CSS常用选择器类型

CSS常用选择器类型

ref:《HTML & CSS设计与构建网站》 p.227

Android 使用 Pull 解析XML

Andoid解析XML除了传统的DOM和SAX外还提供了一种独有的Pull方式。Pull方式跟SAX非常类似,也使用事件驱动和流式解析,不需要像DOM那样读取整个XML文档。Pull跟SAX最大的区别是:控制解析事件的结束。Pull是由用户主动获取事件进行处理, 这就意味着你可以随时结束解析过程。而在SAX中,SAX解析器会把事件自动推入注册的事件处理器,用户无法控制这个过程。所以对于移动设备这种资源有限的设备来说,Pull方式可以缩短XML解析的时间,因为有时候我们可能只需要处理部分XML后主动结束解析,但这是SAX无法做到的。 一个例子 首先在asserts目录下建立需要解析的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<persons>

    <person id="1" >
        <name>lnmcc</name>
        <age>20</age>
    </person>

    <person id="2" >
        <name>wangsijie</name>
        <age>30</age>
    </person>
    
    <person id="3" >
        <name>Jack</name>
        <age>90</age>
    </person>
    
</persons>

MainActivity.java:

public class MainActivity extends Activity {

	public class Person {
		private int id;
		private String name;
		private int age;

		public void setId(int id) {
			this.id = id;
		}

		public void setName(String name) {
			this.name = name;
		}

		public void setAge(int age) {
			this.age = age;
		}

		public int getId() {
			return id;
		}

		public String getName() {
			return name;
		}

		public int getAge() {
			return age;
		}
		
		@Override
		public String toString() {
			return "Person: id = " + id + " name = " + name + " age = " + age + "\n";
		}
	}

	ArrayList persons = null;
	Person newPerson = null;
	TextView tv = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv = (TextView) findViewById(R.id.textView);
		parseXml();
	}

	private void parseXml() {
		try {
			InputStream inStream = getAssets().open("persons.xml");
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			XmlPullParser parser = factory.newPullParser();
			parser.setInput(inStream, "UTF-8");
			int eventType = parser.getEventType();
			boolean docEnd = false;
			
			while (!docEnd) {
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					Log.e("PersonInfo", "Document Start");
					persons = new ArrayList();
					break;
				case XmlPullParser.START_TAG:
					Log.e("PersonInfo", "Tag Start");
					String name = parser.getName();
					if (name.equalsIgnoreCase("person")) {
						newPerson = new Person();
						newPerson.setId(Integer.valueOf(parser
								.getAttributeValue(null, "id")));
					} else if (newPerson != null) {
						if (name.equalsIgnoreCase("name")) {
							newPerson.setName(parser.nextText().trim());
						} else if (name.equalsIgnoreCase("age")) {
							newPerson.setAge(Integer.valueOf(parser.nextText().trim()));
						}
					}
					break;
				case XmlPullParser.END_TAG:
					Log.e("PersonInfo", "Tag End");
					if (newPerson != null
							&& parser.getName().equalsIgnoreCase("person")) {
						persons.add(newPerson);
						newPerson = null;
					}
					break;
				case XmlPullParser.END_DOCUMENT:
					Log.e("PersonInfo", "Document End");
					docEnd = true;
					printPersons(); // 解析完成,输出所以人的信息
					break;
				default:
					break;
				}
				eventType = parser.next();
			}

		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void printPersons() {
		Iterator iter = persons.iterator();
		StringBuffer sb = new StringBuffer();
		while(iter.hasNext()) {
			String info = iter.next().toString();
			Log.e("PersonInfo", info);
			sb.append(info);
		}
		tv.setText(sb.toString());
	}
}

github: https://github.com/lnmcc/ParseXmlUsePull.git