1.怎么使用AsyncTask+Handler传值
地址:http://www.oschina.net/code/snippet_725438_49858
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
布局文件:
<LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
xmlns:tools=
"http://schemas.android.com/tools"
android:layout_width=
"match_parent"
android:layout_height=
"match_parent"
android:orientation=
"vertical"
>
<ImageView android:id=
"@+id/im1"
android:layout_width=
"wrap_content"
android:layout_height=
"wrap_content"
android:src=
"@drawable/ic_launcher"
/>
<ImageView android:id=
"@+id/im2"
android:layout_width=
"wrap_content"
android:layout_height=
"wrap_content"
android:src=
"@drawable/ic_launcher"
/>
</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
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
132
133
134
135
136
137
138
139
140
|
2
.第一种,回调方法方式:
package
com.androidwallpaper;
import
java.io.FileNotFoundException;
import
java.io.IOException;
import
java.io.InputStream;
import
java.net.HttpURLConnection;
import
java.net.MalformedURLException;
import
java.net.URL;
import
java.util.concurrent.ExecutorService;
import
java.util.concurrent.Executors;
import
android.net.Uri;
import
android.os.AsyncTask;
import
android.os.Bundle;
import
android.os.Handler;
import
android.os.Message;
import
android.app.Activity;
import
android.app.WallpaperManager;
import
android.content.Intent;
import
android.graphics.Bitmap;
import
android.graphics.BitmapFactory;
import
android.view.Menu;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.ImageView;
import
android.widget.ProgressBar;
import
android.widget.Toast;
public
class
MainActivity
extends
Activity
implements
OnClickListener{
ImageView im1;
ImageView im2;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
im1 = (ImageView) findViewById(R.id.im1);
im2 = (ImageView) findViewById(R.id.im2);
try
{
final
ImageViewAsyncTask task =
new
ImageViewAsyncTask(
"http://static.oschina.net/uploads/ad/new_banner_one_ronglianyun_WrqUs.png"
);
task.setOnDataFinishedListener(
new
OnDataFinishedListener() {
@Override
public
void
onDataSuccessfully(Object data) {
try
{
im1.setImageBitmap((Bitmap) data);
}
catch
(Exception e) {
e.printStackTrace();
}
}
@Override
public
void
onDataFailed() {
Toast.makeText(MainActivity.
this
,
"加载失败!"
, Toast.LENGTH_SHORT).show();
}
});
task.execute();
}
catch
(Exception e) {
e.printStackTrace();
}
}
class
ImageViewAsyncTask
extends
AsyncTask<String, Integer, Bitmap> {
String mUrl;
OnDataFinishedListener onDataFinishedListener;
public
ImageViewAsyncTask(String url){
this
.mUrl = url;
}
public
void
setOnDataFinishedListener(
OnDataFinishedListener onDataFinishedListener) {
this
.onDataFinishedListener = onDataFinishedListener;
}
@Override
protected
Bitmap doInBackground(String... params) {
InputStream ins =
null
;
Bitmap bitmap =
null
;
try
{
URL url =
new
URL(mUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if
(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
ins = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(ins);
return
bitmap;
}
}
catch
(MalformedURLException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
finally
{
if
(ins!=
null
){
try
{
ins.close();
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
return
null
;
}
@Override
protected
void
onPreExecute() {
super
.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected
void
onPostExecute(Bitmap result) {
progressBar.setVisibility(View.GONE);
if
(result!=
null
){
onDataFinishedListener.onDataSuccessfully(result);
}
else
{
onDataFinishedListener.onDataFailed();
}
}
@Override
protected
void
onProgressUpdate(Integer... values) {
super
.onProgressUpdate(values);
}
}
}
|
1
2
3
4
5
6
7
8
|
回调接口:
public
interface
OnDataFinishedListener {
public
void
onDataSuccessfully(Object data);
public
void
onDataFailed();
}
|
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
|
第二种:使用handler:
1
.修改ImageViewAsyncTask:
public
class
ImageViewAsyncTask
extends
AsyncTask<String, Integer, Bitmap> {
String mUrl;
Handler mHandler;
public
ImageViewAsyncTask(String url,Handler handler){
this
.mUrl = url;
this
.mHandler = handler;
}
@Override
protected
Bitmap doInBackground(String... params) {
InputStream ins =
null
;
Bitmap bitmap =
null
;
try
{
URL url =
new
URL(mUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if
(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
ins = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(ins);
return
bitmap;
}
}
catch
(MalformedURLException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
finally
{
if
(ins!=
null
){
try
{
ins.close();
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
return
null
;
}
@Override
protected
void
onPreExecute() {
super
.onPreExecute();
}
@Override
protected
void
onPostExecute(Bitmap result) {
super
.onPostExecute(result);
Message msg = mHandler.obtainMessage();
if
(result!=
null
){
msg.what =
1
;
msg.obj = result;
}
else
{
msg.what =
2
;
}
mHandler.sendMessage(msg);
}
@Override
protected
void
onProgressUpdate(Integer... values) {
super
.onProgressUpdate(values);
}
}
2
.调用方式:
ImageViewAsyncTask task2 =
new
ImageViewAsyncTask(
"http://static.oschina.net/uploads/ad/new_banner_one_ronglianyun_WrqUs.png"
, handler);
task2.execute();
Handler handler =
new
Handler(){
@Override
public
void
handleMessage(Message msg) {
switch
(msg.what) {
case
1
:
Bitmap bitmap = (Bitmap) msg.obj;
im2.setImageBitmap(bitmap);
break
;
default
:
break
;
}
}
};
|
Android Volley完全解析(一),初识Volley的基本用法
Android Volley完全解析(二),使用Volley加载网络图片
Android Volley完全解析(三),定制自己的Request
Android Volley完全解析(四),带你从源码的角度理解Volley
3.json解析 异步请求之后需要把返回的值变成对象 使用gson
一、 谷歌GSON这个Java类库可以把Java对象转换成JSON,也可以把JSON字符串转换成一个相等的Java对象。Gson支持任意复杂Java对象包括没有源代码的对象。
二、Gson解析Json步骤
A、服务器端将数据转换成json字符串
首先、服务器端项目要导入Gson的jar包到BuiltPath中。(
Gson的jar:http://code.google.com/p/google-gson/ 我们还可以下载gson的帮助文档)
然后将数据转为json字符串,核心函数是:
public static String createJsonString(Object value)
{
Gson gson = new Gson();
String str = gson.toJson(value);
return str;
}
B、客户端将json字符串转换为相应的javaBean
首先客户端也要导入gson的两个jar包,json的jar就不需要导入了(因为android项目中已经集成了json的jar包所以这里无需导入)
1、客户端获取json字符串
public class HttpUtil
{
public static String getJsonContent(String urlStr)
{
try
{// 获取HttpURLConnection连接对象
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
// 设置连接属性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
// 获取相应码
int respCode = httpConn.getResponseCode();
if (respCode == 200)
{
return ConvertStream2Json(httpConn.getInputStream());
}
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
private static String ConvertStream2Json(InputStream inputStream)
{
String jsonStr = "";
// ByteArrayOutputStream相当于内存输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
// 将输入流转移到内存输出流中
try
{
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
{
out.write(buffer, 0, len);
}
// 将内存流转换为字符串
jsonStr = new String(out.toByteArray());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonStr;
}
}
2、使用泛型获取javaBean(核心函数)
public static <T> T getPerson(String jsonString, Class<T> cls) {
T t = null;
try {
Gson gson = new Gson();
t = gson.fromJson(jsonString, cls);
} catch (Exception e) {
// TODO: handle exception
}
return t;
}
public static <T> List<T> getPersons(String jsonString, Class<T> cls) {
List<T> list = new ArrayList<T>();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken<List<cls>>() {
}.getType());
} catch (Exception e) {
}
return list;
}
public static List<Map<String, Object>> listKeyMaps(String jsonString) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString,
new TypeToken<List<Map<String, Object>>>() {
}.getType());
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
原文地址:http://blog.sina.com.cn/s/blog_7ffb8dd501013q9c.html
这里介绍的是泛型 我觉得很好,或者你也可以用到什么什么的时候就解析什么 随便
public class GetHttp { public static String RequstGetHttp(String strUrl) { URL url = null; String result=""; try { url = new URL(strUrl); HttpURLConnection urlconn = (HttpURLConnection) url.openConnection(); urlconn.setConnectTimeout(1000); urlconn.setReadTimeout(15000); urlconn.connect();// 链接服务器并发送消息 // 开始接收返回的数据 InputStreamReader is = new InputStreamReader(urlconn.getInputStream()); BufferedReader bufferedReader = new BufferedReader(is); String readLine = ""; while ((readLine = bufferedReader.readLine()) != null) { result += readLine; } is.close(); urlconn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
public class PostHttp { public static String RequstPostHttp(String strUrl) { URL url = null; String result=""; try { url = new URL(strUrl); HttpURLConnection urlconn = (HttpURLConnection) url.openConnection(); urlconn.setDoInput(true);// 设置输入流采用字节流模式 urlconn.setDoOutput(true); urlconn.setRequestMethod("POST"); urlconn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlconn.setRequestProperty("Charset", "UTF-8"); urlconn.setConnectTimeout(10000); urlconn.setReadTimeout(15000); urlconn.connect();// 链接服务器并发送消息 OutputStream outStream = urlconn.getOutputStream(); outStream.flush();// 发送,清除缓存 outStream.close();// 关闭 // 开始接收返回的数据 InputStream is = urlconn.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String readLine = ""; while ((readLine = bufferedReader.readLine()) != null) { result += readLine; } bufferedReader.close(); urlconn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
c.在activity里面启动子线程,在handler里面对返回结果进行处理
下面的需要去弄清楚AsyncTask的原理le