一:介绍
xutils是一个热门的安卓开发框架,封装了网络请求工具,注解工具,数据库工具,日志打印工具.Android6.0之后sdk放弃了httpclient,所以xutils2.6中因为底层用的httpclient所以在xutils3之后把网络请求全部换成了httpurlconnection,从而与Android6.0更好的兼容,下面就介绍xutils3之后版本使用方法
二:引入xutils3并初始化
1.引入xutils3:用Androidstudio新建工程之后,引入xutils3,方法如下,点击ok之后等待一会就可以了! eclipse可以在github上下载源码,然后导入依赖即可
2.初始化xutils3
新建一个application,在oncreat方法中初始化
@Override
public void onCreate() {
super.onCreate();
myApp = this;
x.Ext.init(this);//初始化sdk
x.Ext.setDebug(true);//处于开发阶段,设置打印日志
}
android:name=".MyApp"
三:使用最多的就是网络工具类,先看一下网络请求
1.get请求示例,与xutils2.6版本的httputils不一样了,而且必须要重写的回调方法增多了,可以想象如果一个activity中发起了多次这样的网络请求,那样会产生很多的重复代码,所以后面会对回调封装一下,把回调方法全部封装到一个类当中,后面可以下载demo,demo比较全而且详细!
private void get() {
String path = "http://mobileapi.72g.com/index.php?tp=andv4/index_new&op=jifen&point=100";
RequestParams params = new RequestParams(path);
//x.http().get(params, new CommonStringCallback(handler, 1));
x.http().get(params, new Callback.CommonCallback() {
@Override
public void onSuccess(String result) {
LogUtil.e(result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
LogUtil.e("onError" + ex.getMessage());
}
@Override
public void onCancelled(CancelledException cex) {
LogUtil.e("onCancelled");
}
//这个回调不管是否请求成功最后都一定会执行
@Override
public void onFinished() {
LogUtil.e("onFinished");
}
});
}
2.post请求,就是加了参数
private void post() {
//百科 post: rows=15&page=0&type=16
String BAIKEPATH = "http://sns.maimaicha.com/api?apikey=b4f4ee31a8b9acc866ef2afb754c33e6&format=json&method=news.getListByType";
RequestParams params = new RequestParams(BAIKEPATH);
//默认是启用缓存,这里设置没有缓存
params.setUseCookie(false);
params.addBodyParameter("rows", "15");
params.addBodyParameter("page", "0");
params.addBodyParameter("type", "16");
x.http().post(params, new Callback.CommonCallback() {
@Override
public void onSuccess(String result) {
LogUtil.e(result);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
});
}
(1).不需要其他操作的:
x.image().bind(img_show, "http://d.hiphotos.baidu.com/image/pic/item/562c11dfa9ec8a13f075f10cf303918fa1ecc0eb.jpg");
x.image().bind(img_show, "http://d.hiphotos.baidu.com/image/pic/item/562c11dfa9ec8a13f075f10cf303918fa1ecc0eb.jpg", new Callback.CommonCallback() {
@Override
public void onSuccess(Drawable result) {
//可以在这里对下载的图片进行额外操作,比如写进文件
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
});
ImageOptions.Builder builder = new ImageOptions.Builder();
builder.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.a));//添加动画效果
builder.setRadius(30);//设置圆角
manager.bind(img_show, "http://d.hiphotos.baidu.com/image/pic/item/562c11dfa9ec8a13f075f10cf303918fa1ecc0eb.jpg", builder.build());
ImageManager manager = x.image();//可以重复使用,不需要再次创建
manager.bind(img_show,"http://d.hiphotos.baidu.com/image/pic/item/562c11dfa9ec8a13f075f10cf303918fa1ecc0eb.jpg");
private void downloadFile() {
//进度对话框
dialog = new ProgressDialog(context);
dialog.setTitle("下载进度");
dialog.setMessage("拼命下载中");
dialog.setMax(100);
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//开始下载
String pathUrl = "http://down.72g.com/upload/app/201407/201407150923238621.apk";
RequestParams params = new RequestParams(pathUrl);
dialog.show();
x.http().get(params, new Callback.CommonCallback() {
@Override
public void onSuccess(File result) {
dialog.dismiss();
File file = result;
if (file.exists()) {
//设置安装路径
AutoInstall.setUrl(file.getAbsolutePath());
//调用系统安装界面进行安装
AutoInstall.install(context);
} else {
Toast.makeText(context, "该安装包不存在", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
LogUtil.e("onError");
}
@Override
public void onCancelled(CancelledException cex) {
dialog.dismiss();
}
@Override
public void onFinished() {
LogUtil.e("onFinished");
}
});
}
public class MainActivity extends AppCompatActivity {
private Context context = this;
//注解
@ViewInject(R.id.img_show)
private ImageView img_show;
@ViewInject(R.id.txt)
private TextView txt;
//多个按钮点击事件注解
@Event(value = {R.id.btn1, R.id.btn2})
private void onClick(View view) {
switch (view.getId()) {
case R.id.btn1:
Toast.makeText(context, "点击了", Toast.LENGTH_SHORT).show();
break;
case R.id.btn2:
Toast.makeText(context, "点击了第二个", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
x.view().inject(this);
txt.setText("我是注解TextView");
}
}
LogUtil.e("onError");
封装原理:因为每次网络请求都会有4个必须写的回调函数,这样如果有多个网络请求,那么就会产生很多的重复代码,这里对网络请求的回调进行封装,用handler传回请求的结果(一般是list集合),用what值区分不同的网络请求,看代码.对于传回网络请求的结果,大家也可以用EventBus框架,EventBus耦合度极低.
这是网络请求回调的封装类
package com.zidiv.xutils3demo;
import android.os.Handler;
import android.os.Message;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import java.util.List;
/**
* Created by Administrator on 2016/2/18.
*/
public class CommonStringCallback implements Callback.CommonCallback {
private Handler handler;
private int what;
public CommonStringCallback(Handler handler, int what) {
this.handler = handler;
this.what = what;
}
@Override
public void onSuccess(String result) {
//json解析
JSONObject object = JSON.parseObject(result);
JSONArray array = object.getJSONArray("info");
List list = JSON.parseArray(array.toJSONString(), Bean.class);
Message message = Message.obtain();
message.what = what;
message.obj = list;
handler.sendMessage(message);
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
LogUtil.e("请求失败:" + ex);
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
}
String path = "http://mobileapi.72g.com/index.php?tp=andv4/index_new&op=jifen&point=100";
RequestParams params = new RequestParams(path);
x.http().get(params, new CommonStringCallback(handler, 1));
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
List list = (List) msg.obj;
Toast.makeText(context, list.get(0).getName(), Toast.LENGTH_LONG).show();
break;
}
}
};