第一步:導入volley 和gson的jarhtml
第二步:<uses-permission android:name="android.permission.INTERNET" />android
第三步: static 的單例類,用於管理volley中的方法json
public class MySingleton {
private static MySingleton mInstance;
private static Context context;
private RequestQueue mRequestQueue;
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}服務器
private MySingleton(Context mcontext) {
context = mcontext;
mRequestQueue = getRequestQueue();
}app
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {// ApplicationContext確保volley的隊列在app運行中都存在
mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());
}
return mRequestQueue;
}ide
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
}ui
第四步: 自定義Gson請求
public class GsonRequest<T> extends Request<T> {this
private final Listener<T> mListener;
private Gson mGson;
private Class<T> mClass;url
public GsonRequest(String url, Class<T> mClass, Listener<T> mListener,ErrorListener listener) {
this(Method.GET, url, mClass, mListener, listener);
}spa
public GsonRequest(int method, String url, Class<T> mClass,
Listener<T> mListener, ErrorListener listener) {
super(method, url, listener);
mGson = new Gson();
this.mClass = mClass;
this.mListener = mListener;
}
@Override//將服務器響應的數據解析出來,而後Gson的fromJson方法將數據組裝成對象,在工做線程中運行
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(mGson.fromJson(jsonString, mClass),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
//最終的數據進行回調給ui線程
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}
案例:
url :"http://www.weather.com.cn/data/sk/101010100.html"
return result:
{"weatherinfo": {"city":"北京","cityid":"101010100","temp":"19",
"WD":"南風","WS":"2級","SD":"43%", "WSE":"2","time":"19:45","isRadar":"1",
"Radar":"JC_RADAR_AZ9010_JB"}
}
第五步:定義實體類和引用類(根據實際返回結果寫)
/**
* 實體類的引用類
*
* @author Administrator
*
*/
public class Entity_Quote {
private Entity weatherinfo;
public Entity getEntity() {
return entity;
}
public void setEntity(Entity entity) {
this.entity = entity;
}
}
/**
* 實體類
* @author Administrator
*
*/
public class Entity {
private String city;
private String temp;
private String time;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
第六步:activity中使用
public class MainActivity extends Activity {
TextView tv;
public String url= "http://www.weather.com.cn/data/sk/101010100.html";
public final static String TAG=MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.mian_tv);
sendRequest();
}
//volley適合數據量小且通訊頻繁,可是不可用數據大的操做,如流媒體,下載文件(downloadManager)等。
private void sendRequest() {
GsonRequest<Entity_Quote> gsonRequest=
new GsonRequest<Entity_Quote>(url,Entity_Quote.class,new Listener<Entity_Quote>() { @Override public void onResponse(Entity_Quote quote) {//返回一個引用類,經過引用類拿到實體類 Entity entity=quote.getEntity(); tv.setText(entity.getCity()+""+entity.getTemp()+""+entity.getTime()); } }, new ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("TAG", error.getMessage(), error); } }); gsonRequest.setTag(TAG);//添加標記,便於取消 MySingleton.getInstance(this).addToRequestQueue(gsonRequest); //能夠在任何線程中添加一個請求, 可是響應結果都是返回在主線程中 } @Override protected void onStop() { RequestQueue mQueue=MySingleton.getInstance(this.getApplicationContext()).getRequestQueue(); if(mQueue!=null){ mQueue.cancelAll(TAG);//取消用TAG標記的request } super.onStop(); }}