后台任务封装:在没有网络的时候也可以修改用户名、头像等操作
private void doOk() {
String text = etName.getText().toString().trim();
if (TextUtils.isEmpty(text)) {
ToastUtil.show(getActivity(), "名字不能为空");
return;
}
// 数据更新
account.setName(text);
dao.updateAccount(account);
String url = "http://192.168.1.101:8080/ChatServer/user/name";
Map<String, String> headers = new HashMap<String, String>();
headers.put("account", account.getAccount());
headers.put("token", account.getToken());
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("name", text);
// 1. 将请求加入到后台任务
// 1) 封装
NetTask request = new NetTask();
request.setUrl(url);
request.setMethod(0);
request.setHeaders(headers);
request.setParameters(parameters);
// 2) 序列化
String outPath = DirUtil.getTaskDir(getActivity()) + "/"
+ System.currentTimeMillis();
try {
SerializableUtil.write(request, outPath);
} catch (Exception e) {
e.printStackTrace();
}
// 3) 存储到数据库记录
BackTask task = new BackTask();
task.setOwner(account.getAccount());
task.setPath(outPath);
task.setState(0);
new BackTaskDao(getActivity()).addTask(task);
// 开启服务
getActivity().startService(
new Intent(getActivity(), BackgroundService.class));
// 2. 页面跳转
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
getActivity().finish();
}