您的位置:首页 > 移动开发 > Android开发

Volley从零创建一个简单的文字传输

2015-07-23 00:37 525 查看

一、导入volley的jar包

           首先需要将Volley的jar包准备好,如果你的电脑上装有Git,可以使用如下命令下载Volley的 源码:git clone https://android.googlesource.com/platform/frameworks/volley 下载完成后将它导入到你的Eclipse工程里,然后再导出一个jar包就可以了。

同时也可以用这个jar包,下载地址是:Volley的jar包

二、运用Application单例模式创建唯一RequestQueue

        创建RequestQueue的原则:在项目中mQueue 只需要一个对象即可,new RequestQueue对象对资源是一种浪费,我们应该在application中以单例化的模式保存这样一个对象,方便在整个APP中调用这个项目,以下是MyApplication配置代码(记得最后在AndroidManifist.xml中配置name属性)

<span style="font-size:14px;">import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

import android.app.Application;

public class MyApplication extends Application {

private RequestQueue reqQueue;

@Override
public void onCreate() {
super.onCreate();
}

public RequestQueue getReqQueue() {
if (reqQueue == null) {
reqQueue = Volley.newRequestQueue(getApplicationContext());
}
return reqQueue;
}

}</span>

三、创建MyVolley网络传输类

     在MyVolley这个类中获取到属于整个App的RequestQueue对象,然后由于我们此次写的是文字类型传输,所以构造了两个方法,一个是返回String类型的,另一个是返回jsonObject类型的(jsonArray类似),类中还加入了给request添加标签的方法,方便requestQueue根据标签删除对应的request,这个能够方便的结合对应Activity的生命周期,避免退出后后台还在运行网络请求浪费资源

<span style="font-size:14px;">import org.json.JSONObject;

import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;

public class MyVolley {

private RequestQueue queue;
private Context context;

public MyVolley(Context context, RequestQueue queue) {
this.context = context;
this.queue = queue;
}

public void getJsonFromNet(String url, String tag, final TextView t) {
JsonObjectRequest jsonRequest = new JsonObjectRequest(
Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
t.setText(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(
context,
VolleyErrorHelper.getErrorMessage(context,
error), Toast.LENGTH_SHORT).show();
}
});
addToRequestQueue(jsonRequest, tag);

}

public void getStringFromNet(String url, String tag, final TextView t) {
StringRequest strRequest = new StringRequest(Request.Method.GET, url,
new Listener<String>() {

@Override
public void onResponse(String response) {
t.setText(response);
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.getMessage(),
Toast.LENGTH_SHORT).show();
}

});
addToRequestQueue(strRequest, tag);
}

/**
* 为请求添加标签并置于队列中
*
* @param req
* @param tag
*/
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(tag);
queue.add(req);
}

/**
* 删除标签项的请求
*
* @param tag
*/
public void cancelRequest(String tag) {
queue.cancelAll(tag);
}
}</span>


          另外,对于访问出错返回的数据,并不是我们想展现给用户的信息,其中含有很多Exception异常信息,需要我们按照异常分类来提示用户,这样我们就建立了一个VolleyErrorHelper类,来处理返回异常的Exception 如下

<span style="font-size:14px;">import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;

public class VolleyErrorHelper {

String error;

public static String getErrorMessage(Context context, Object error) {
if (error instanceof TimeoutError) {
return context.getResources().getString(
R.string.generic_server_down);
} else if (isServerProblem(error)) {
return context.getResources().getString(R.string.generic_error);
} else if (isNetworkProblem(error)) {
return context.getResources().getString(R.string.no_internet);
}
return context.getResources().getString(R.string.generic_error);
}

private static boolean isNetworkProblem(Object error) {
return (error instanceof NetworkError)
|| (error instanceof NoConnectionError);
}

private static boolean isServerProblem(Object error) {
return (error instanceof ServerError)
|| (error instanceof AuthFailureError);
}

}
</span>

     其中的strings.xml的xml配置如下

<string name="no_internet">无网络连接~!</string>
<string name="generic_server_down">连接服务器失败~!</string>
<string name="generic_error">网络异常,请稍后再试~!</string></span>


四、UI线程中传入url启用MyVolley

     为了简单测试我们的MainActivity中并没有复杂的业务逻辑和控件,只有一个Button和TextView,分别用来点击开始和现实结果,其中TextView的中间改变模拟了类似AsyncTask的onPreExecute的效果

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.android.volley.RequestQueue;

public class MainActivity extends Activity {

private RequestQueue queue;
private TextView text;
private MyVolley volley;
private  String tag = "json";
String url = "http://m.weather.com.cn/data/101010100.html"; //这个能返回一个jsonObject的网页url

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApplication app = (MyApplication) getApplication();
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.myText);
queue = app.getReqQueue();
volley = new MyVolley(this,queue);
}

public void doD(View v){
text.setText("..........");
volley.getJsonFromNet(url, tag, text);
}

@Override
protected void onStop() {
super.onStop();
volley.cancelRequest(tag);
}
}</span><span style="font-size:12px;">
</span>
  

    以上就是我们简单的对文字版Volley的网络框架做了一个小的总结,后续会追加对图片的Volley框架应用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 框架 Volley 移动