把VolleyInterface这个抽象类写成内部接口会不会更好一点?
把VolleyInterface这个抽象类写成内部接口会不会更好一点?
我把它写成了MyVolleyRequest这个类的内部接口(Callback),感觉看起来更清晰,代码少了。
这样和视频中的抽象类相比,有什么优劣之处吗?
MyVolleyRequest.java :
```Java
/** * Volley的二次回调封装 */ public class MyVolleyRequest { private Context mContext; private Response.Listener<String> mListener; private Response.ErrorListener mErrorListener; public MyVolleyRequest(Context context, final Callback callback) { mContext = context; mListener = new Response.Listener<String>() { @Override public void onResponse(String response) { callback.onSuccess(response); } }; mErrorListener = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { callback.onError(error); } }; } public void requestGet(String url, String tag) { //先取消已有的网络请求,避免重复请求 MyApplication.getRequestQueue().cancelAll(tag); StringRequest stringRequest = new StringRequest(Request.Method.GET, url, mListener, mErrorListener); stringRequest.setTag(tag); MyApplication.getRequestQueue().add(stringRequest); //启动该全局队列中的调度程序(dispatchers) MyApplication.getRequestQueue().start(); } public interface Callback { void onSuccess(String response); void onError(VolleyError error); } }
```
MainActivity.java :
```Java
public class VolleyDemoActivity extends AppCompatActivity { public static final String VOLLEY_TAG = "volley_tag"; public static final String JUHE_APPKEY = "xxxxxxxxxxxxxxxxxxxxx"; public static final String JUHE_API_URL = "http://v.juhe.cn/postcode/query"; /* * 聚合数据查询邮编对应的地址的url,用于测试 * 请求示例:http://v.juhe.cn/postcode/query?postcode=邮编&key=申请的KEY */ private String postcode = "210044"; private String url_GET = JUHE_API_URL + "?postcode=" + postcode + "&key=" + JUHE_APPKEY; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //MyVolleyRequest GET myVolleyRequestDemo_GET(); myVolleyRequestDemo_POST(); } //Volley二次回调封装测试 private void myVolleyRequestDemo_GET() { MyVolleyRequest myVolleyRequest = new MyVolleyRequest(this, new MyVolleyRequest.Callback() { @Override public void onSuccess(String response) { Log.i("### onSuccess", "GET_MyVolleyRequest" + response); } @Override public void onError(VolleyError error) { } }); myVolleyRequest.requestGet(url_GET, "my_get_" + VOLLEY_TAG); } }
```
结尾吐槽以下,竟然不支持Markdown!