Android 学习(一)
一、Android系统框架介绍
1
2
3
4
5
6
7
8
|
Intent intent = new Intent();
// 在意图中传递数据
intent.putExtra( "name" , "张三" );
intent.putExtra( "age" , 23 );
intent.putExtra( "address" , "北京" );
intent.setClass(Main. this , OtherActivity. class );
// 启动意图
startActivity(intent);
|
1
2
3
4
|
Intent intent = getIntent();
int age = intent.getIntExtra( "age" , 0 );
String name = intent.getStringExtra( "name" );
String address = intent.getStringExtra( "address" );
|
1
2
3
4
5
|
Intent intent = new Intent();
int three = Integer.parseInt(editText.getText().toString());
intent.putExtra( "three" , three);
//通过Intent对象返回结果,setResult方法,
setResult( 2 , intent);
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
button.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int a = Integer.parseInt(one.getText().toString());
int b = Integer.parseInt(two.getText().toString());
Intent intent = new Intent(Main. this , OtherActivity. class );
intent.putExtra( "a" , a);
intent.putExtra( "b" , b);
//启动Intent
startActivityForResult(intent, REQUESTCODE); // 表示可以返回结果
}
});
}
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super .onActivityResult(requestCode, resultCode, data);
if (resultCode== 2 ){
if (requestCode==REQUESTCODE){
int three = data.getIntExtra( "three" , 0 );
result.setText(String.valueOf(three));
}
}
}
|
1
|
setContentView(R.layout.main);
|
·线性布局LinearLayout :
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
package com.http.get;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
private static String URL_PATH = "http://192.168.0.102:8080/myhttp/pro1.png" ;
public HttpUtils() {
// TODO Auto-generated constructor stub
}
public static void saveImageToDisk() {
InputStream inputStream = getInputStream();
byte [] data = new byte [ 1024 ];
int len = 0 ;
FileOutputStream fileOutputStream = null ;
try {
fileOutputStream = new FileOutputStream( "C:\\test.png" );
while ((len = inputStream.read(data)) != - 1 ) {
fileOutputStream.write(data, 0 , len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (inputStream != null ) {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fileOutputStream != null ) {
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* 获得服务器端的数据,以InputStream形式返回
* @return
*/
public static InputStream getInputStream() {
InputStream inputStream = null ;
HttpURLConnection httpURLConnection = null ;
try {
URL url = new URL(URL_PATH);
if (url != null ) {
httpURLConnection = (HttpURLConnection) url.openConnection();
// 设置连接网络的超时时间
httpURLConnection.setConnectTimeout( 3000 );
httpURLConnection.setDoInput( true );
// 表示设置本次http请求使用GET方式请求
httpURLConnection.setRequestMethod( "GET" );
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200 ) {
// 从服务器获得一个输入流
inputStream = httpURLConnection.getInputStream();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inputStream;
}
public static void main(String[] args) {
// 从服务器获得图片保存到本地
saveImageToDisk();
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
|
package com.http.post;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpUtils {
// 请求服务器端的url
private static String PATH = "http://192.168.0.102:8080/myhttp/servlet/LoginAction" ;
private static URL url;
public HttpUtils() {
// TODO Auto-generated constructor stub
}
static {
try {
url = new URL(PATH);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param params
* 填写的url的参数
* @param encode
* 字节编码
* @return
*/
public static String sendPostMessage(Map<String, String> params,
String encode) {
// 作为StringBuffer初始化的字符串
StringBuffer buffer = new StringBuffer();
try {
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
// 完成转码操作
buffer.append(entry.getKey()).append( "=" ).append(
URLEncoder.encode(entry.getValue(), encode))
.append( "&" );
}
buffer.deleteCharAt(buffer.length() - 1 );
}
// System.out.println(buffer.toString());
// 删除掉最有一个&
System.out.println( "-->>" +buffer.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setConnectTimeout( 3000 );
urlConnection.setRequestMethod( "POST" );
urlConnection.setDoInput( true ); // 表示从服务器获取数据
urlConnection.setDoOutput( true ); // 表示向服务器写数据
// 获得上传信息的字节大小以及长度
byte [] mydata = buffer.toString().getBytes();
// 表示设置请求体的类型是文本类型
urlConnection.setRequestProperty( "Content-Type" ,
"application/x-www-form-urlencoded" );
urlConnection.setRequestProperty( "Content-Length" ,
String.valueOf(mydata.length));
// 获得输出流,向服务器输出数据
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(mydata, 0 ,mydata.length);
outputStream.close();
// 获得服务器响应的结果和状态码
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200 ) {
return changeInputStream(urlConnection.getInputStream(), encode);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "" ;
}
/**
* 将一个输入流转换成指定编码的字符串
*
* @param inputStream
* @param encode
* @return
*/
private static String changeInputStream(InputStream inputStream,
String encode) {
// TODO Auto-generated method stub
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte [] data = new byte [ 1024 ];
int len = 0 ;
String result = "" ;
if (inputStream != null ) {
try {
while ((len = inputStream.read(data)) != - 1 ) {
outputStream.write(data, 0 , len);
}
result = new String(outputStream.toByteArray(), encode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, String> params = new HashMap<String, String>();
params.put( "username" , "admin" );
params.put( "password" , "1234" );
String result = HttpUtils.sendPostMessage(params, "utf-8" );
System.out.println( "--result->>" + result);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
package com.http.post;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
public HttpUtils() {
// TODO Auto-generated constructor stub
}
public static String sendHttpClientPost(String path,
Map<String, String> map, String encode) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
if (map != null && !map.isEmpty()) {
for (Map.Entry<String, String> entry : map.entrySet()) {
list.add( new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
}
try {
// 实现将请求的参数封装到表单中,请求体中
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
// 使用Post方式提交数据
HttpPost httpPost = new HttpPost(path);
httpPost.setEntity(entity);
// 指定post请求
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200 ) {
return changeInputStream(httpResponse.getEntity().getContent(),
encode);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "" ;
}
/**
* 将一个输入流转换成指定编码的字符串
*
* @param inputStream
* @param encode
* @return
*/
public static String changeInputStream(InputStream inputStream,
String encode) {
// TODO Auto-generated method stub
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte [] data = new byte [ 1024 ];
int len = 0 ;
String result = "" ;
if (inputStream != null ) {
try {
while ((len = inputStream.read(data)) != - 1 ) {
outputStream.write(data, 0 , len);
}
result = new String(outputStream.toByteArray(), encode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String path = "http://192.168.0.102:8080/myhttp/servlet/LoginAction" ;
Map<String, String> params = new HashMap<String, String>();
params.put( "username" , "admin" );
params.put( "password" , "123" );
String result = HttpUtils.sendHttpClientPost(path, params, "utf-8" );
System.out.println( "-->>" +result);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public static void main(String[] args) {
// TODO Auto-generated method stub
String path = "http://192.168.0.102:8080/myhttp/person.xml" ;
InputStream inputStream = HttpUtils.getXML(path);
try {
List<HashMap<String, String>> list = SaxService.readXML(
inputStream, "person" );
for (HashMap<String, String> map : list) {
System.out.println(map.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public static InputStream getXML(String path) {
InputStream inputStream = null ;
try {
URL url = new URL(path);
if (url != null ) {
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout( 3000 );
connection.setDoInput( true );
connection.setRequestMethod( "GET" );
int code = connection.getResponseCode();
if (code == 200 ) {
inputStream = connection.getInputStream();
}
}
} catch (Exception e) {
// TODO: handle exception
}
return inputStream;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public static List<HashMap<String, String>> readXML(
InputStream inputStream, String nodeName) {
try {
// 创建一个解析xml的工厂对象
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser(); // 解析xml
MyHandler handler = new MyHandler(nodeName);
parser.parse(inputStream, handler);
inputStream.close();
return handler.getList();
} catch (Exception e) {
// TODO: handle exception
}
return null ;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
package com.sax.handler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.jar.Attributes.Name;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyHandler extends DefaultHandler {
private HashMap<String, String> map = null ; // 存储单个解析的完整对象
private List<HashMap<String, String>> list = null ; // 存储所有的解析对象
private String currentTag = null ; // 正在解析的元素的标签
private String currentValue = null ; // 解析当前元素的值
private String nodeName = null ; // 解析当前的节点名称
public MyHandler(String nodeName) {
// TODO Auto-generated constructor stub
this .nodeName = nodeName;
}
public List<HashMap<String, String>> getList() {
return list;
}
@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
// 当读到第一个开始标签的时候,会触发这个方法
list = new ArrayList<HashMap<String, String>>();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// 当遇到文档的开头的时候,调用这个方法
if (qName.equals(nodeName)) {
map = new HashMap<String, String>();
}
if (attributes != null && map != null ) {
for ( int i = 0 ; i < attributes.getLength(); i++) {
map.put(attributes.getQName(i), attributes.getValue(i));
}
}
currentTag = qName;
}
@Override
public void characters( char [] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
// 这个方法是用来处理xml文件所读取到的内容
if (currentTag != null && map != null ) {
currentValue = new String(ch, start, length);
if (currentValue != null && !currentValue.trim().equals( "" )
&& !currentValue.trim().equals( "\n" )) {
map.put(currentTag, currentValue);
}
}
currentTag = null ; // 把当前的节点的对应的值和标签设置为空
currentValue = null ;
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
// 遇到结束标记的时候,会调用这个方法
if (qName.equals(nodeName)) {
list.add(map);
map = null ;
}
super .endElement(uri, localName, qName);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public static void main(String[] args) {
// TODO Auto-generated method stub
String path = "http://192.168.0.102:8080/myhttp/person.xml" ;
InputStream inputStream = HttpUtils.getXML(path);
List<Person> list = null ;
try {
list = PullXMLTools.parseXML(inputStream, "utf-8" );
for (Person person : list) {
System.out.println(person.toString());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
package com.pull.domain;
public class Person {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public Person( int id, String name, int age) {
super ();
this .id = id;
this .name = name;
this .age = age;
}
public void setId( int id) {
this .id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this .name = name;
}
public int getAge() {
return age;
}
public void setAge( int age) {
this .age = age;
}
public Person() {
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]" ;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
package com.pull.parser;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import com.pull.domain.Person;
/**
* 主要是使用PULL解析xml
*
* @author jack
*
*/
public class PullXMLTools {
public PullXMLTools() {
// TODO Auto-generated constructor stub
}
/**
* @param inputStream
* 从服务器获取xml文件,以流的形式返回
* @param encode
* 编码格式
* @return
* @throws Exception
*/
public static List<Person> parseXML(InputStream inputStream, String encode)
throws Exception {
List<Person> list = null ;
Person person = null ; // 装载解析每一个person节点的内容
// 创建一个xml解析的工厂
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
// 获得xml解析类的引用
XmlPullParser parser = factory.newPullParser();
parser.setInput(inputStream, encode);
// 获得事件的类型
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<Person>();
break ;
case XmlPullParser.START_TAG:
if ( "person" .equals(parser.getName())) {
person = new Person();
// 取出属性值
int id = Integer.parseInt(parser.getAttributeValue( 0 ));
person.setId(id);
} else if ( "name" .equals(parser.getName())) {
String name = parser.nextText(); // 获取该节点的内容
person.setName(name);
} else if ( "age" .equals(parser.getName())) {
int age = Integer.parseInt(parser.nextText());
person.setAge(age);
}
break ;
case XmlPullParser.END_TAG:
if ( "person" .equals(parser.getName())) {
list.add(person);
person = null ;
}
break ;
}
eventType = parser.next();
}
return list;
}
}
|
Android 学习(一)相关推荐
- Android学习路线
Android学习路线 第一阶段:Java面向对象编程 1.Java基本数据类型与表达式,分支循环. 2.String和StringBuffer的使用.正则表达式. 3.面向对象的抽象,封装,继承 ...
- 一篇文章一张思维导图看懂Android学习最佳路线
一篇文章一张思维导图看懂Android学习最佳路线 先上一张android开发知识点学习路线图思维导图 Android学习路线从4个阶段来对Android的学习过程做一个全面的分析:Android初级 ...
- Android学习系列(10)--App列表之拖拽ListView(上)
研究了很久的拖拽ListView的实现,受益良多,特此与尔共飨. 鉴于这部分内容网上的资料少而简陋,而具体的实现过程或许对大家才有帮助,为了详尽而不失真,我们一步一步分析,分成两篇文章. ...
- Android学习第一书
大家好,我是一名Facebook的工程师,同时也是<第一行代码--Android>的忠实读者. 虽然我最近几年是在国外读书和工作的,但是和很多人一样,我也非常喜欢郭霖的博客以及他写的< ...
- Android学习笔记21:ImageView获取网络图片
Android平台有3种网络接口可以使用,它们分别是:java.net.*(标准java接口).org.apache(Apache接口)和android.net.*(Android网络接口).本文将使 ...
- 四、Android学习第四天——JAVA基础回顾(转)
(转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 四.Android学习第四天--JAVA基础回顾 这才学习Android的 ...
- Android学习-- 基于位置的服务 LBS(基于百度地图Android SDK)--定位SDK
原文:Android学习-- 基于位置的服务 LBS(基于百度地图Android SDK)--定位SDK 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.ne ...
- 我的Android学习体系
我的Android学习之路历经坎坷啊,现在回过头来主要想分享下我学习Android开发所走过的过程中所学会的一些误区和弯路,那些让自己的进步一直很慢的原因,一直没有什么成就的原因,希望其他人可以借鉴我 ...
- 十一、Android学习第十天——项目开始(转)
(转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 十一.Android学习第十天--项目开始 Android知识点的学习告一 ...
- Android学习笔记(七):多个Activity和Intent
根据www.mars-droid.com:Andriod开发视频教学,先跳过书本<Beginning Android 2>的几个章,我是这两个资源一起看,需要进行一下同步.先初步了解一下应 ...
最新文章
- 安装Python3后再安装Python2
- GenericUDAF使用流程记载(转载+自己整理)
- 计算机科学与技术学术报告,Dennis K. Peters学术报告
- linux 7.0查看防火墙状态,centos7查看防火墙状态
- 计算机jsp外文文献,计算机 JSP web 外文翻译 外文文献 .doc
- CentOS7环境下搭建ElasticSearch
- 基于K60/K66/LPC的HC-SR04超声波测距(附带代码)
- 汽车制造MES介绍之3 - AVI车辆识别与调度
- Deep Residual Network
- ipv6 ripng配置
- Android开发-之五大布局
- (转)Google Fonts 的介绍与使用
- 防止孩子使用计算机的软件,如何防止熊孩纸在电脑里乱装软件
- 在售后技术服务里,Kubernetes到底是什么? | 凌云时刻
- 视频教程-Windows Server 2016 身份管理 (MCSA 认证 70-742)-微软认证
- 安装西门子博图一直重启_博图软件常见错误解决方法
- 使用JSONP解决跨域
- LBS与空间索引原理
- hoolilaw特别分享:在美国喝多少酒就算酒驾
- 中联通宣布3G业务10月1日正式商用 套餐共分九档