android线程登录
主入口代码:
package com.tp.soft.app; import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject; import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; import com.tp.soft.http.HttpUtil;
import com.tp.soft.io.IOUtil;
import com.tp.soft.util.Constant; public class MainActivity extends Activity implements OnClickListener{ private EditText mUser,mPwd;
private Button mSumbit;
private ProgressDialog mProgressDialog;
private String user;
private String pwd;
private Handler loginHandler = new Handler(){ @Override
public void handleMessage(Message msg) {
boolean isNetErr = msg.getData().getBoolean("isNetErr");
if(mProgressDialog != null){
mProgressDialog.dismiss();
}
if(isNetErr){
Toast.makeText(MainActivity.this, "当前网络不可用", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "错误的用户名或者密码", Toast.LENGTH_SHORT).show();
}
} }; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); mUser = (EditText) findViewById(R.id.userEdit);
mPwd = (EditText) findViewById(R.id.pwdEdit); mSumbit = (Button) findViewById(R.id.logBtn);
mSumbit.setOnClickListener(this);
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
protected void onDestroy() {
if(mProgressDialog != null){
mProgressDialog.dismiss();
}
super.onDestroy();
} @Override
public void onClick(View v) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("正在登录,请稍等...");
mProgressDialog.show();
user = mUser.getText().toString();
pwd = mPwd.getText().toString();
if(validateInfo(user, pwd)){
Thread loginThread = new Thread(new LoginHandler());
loginThread.start();
} } private boolean validateInfo(String user, String pwd) {
if("".equals(user)){
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
//setMsg("isEmptyUser");
return false;
}
if("".equals(pwd)){
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
//setMsg("isEmptyPwd");
return false;
}
return true;
} private void setMsg(String msg, boolean isHas){
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putBoolean(msg, isHas);
message.setData(bundle);
loginHandler.sendMessage(message);
} private void setInfo(JSONObject obj) {
SharedPreferences sp = this.getSharedPreferences("userInfo", MODE_APPEND);
Editor edit = sp.edit();
try {
edit.putString("LOGIN_NAME", obj.getString("login_name"));
} catch (JSONException e) {
e.printStackTrace();
}
edit.commit();
} /**
* loginState 0(无网络) 1(帐号密码错误) 2(成功)
* @param params
* @param serverPath
* @return
*/
private int validateLogin(Map<String, String> params, String serverPath){
int loginState = ;
HttpResponse response = HttpUtil.getHttpResonse(serverPath, params, Constant.ENCODING);
if(null != response){
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
IOUtil ioUtil = new IOUtil();
try {
String resultJson = ioUtil.getJson(response.getEntity().getContent());
JSONObject jsonObject = new JSONObject(resultJson);
boolean isSuccess = jsonObject.getBoolean("success");
if(isSuccess){
//Result r = JSONArray.parseObject(resultJson, Result.class);
//if(r.isSuccess()){
//setInfo(r);
//}
JSONObject userJson = jsonObject.getJSONObject("data").getJSONObject("user");
setInfo(userJson);
loginState = ;
}else{
loginState = ;
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}else{
loginState = ;
}
}
return loginState;
} class LoginHandler implements Runnable { @Override
public void run() {
String serverPath = Constant.LOGINURL;
Map<String, String> params = new HashMap<String, String>();
params.put("username", user);
params.put("password", pwd);
int status = validateLogin(params, serverPath);
if(status == ){
setMsg("isNetErr", true);
}else if(status == ){
setMsg("isNetErr", false);
}else if(status == ){
Intent intent = new Intent();
intent.setClass(MainActivity.this, ShowActivity.class);
startActivity(intent);
finish();
}
} }
}
HttpClient封装:
package com.tp.soft.http; import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP; import android.util.Log; /**
* httpClient封装
* @author taop
*
*/
public class HttpUtil {
public static HttpResponse getHttpResonse(String serverPath, Map<String, String> params, String encoding){
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
if(null != params && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
} HttpResponse response = null;
try{
HttpPost post = new HttpPost(serverPath);
post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
response = getHttpClient().execute(post);
}catch (ConnectTimeoutException e) {
Log.e("提示", "连接超时");
return null;
} catch (SocketTimeoutException e) {
Log.e("提示", "Socket连接超时");
return null;
} catch (Exception e) {
Log.e("提示", e.getLocalizedMessage());
return null;
} return response;
} public static HttpClient getHttpClient() {
BasicHttpParams httpParams = new BasicHttpParams();
ConnManagerParams.setTimeout(httpParams, );
/* 连接超时 */
HttpConnectionParams.setConnectionTimeout(httpParams, );// 设置请求超时3秒钟
/* 请求超时 */
HttpConnectionParams.setSoTimeout(httpParams, );// 设置等待数据超时时间3秒钟
HttpClient client = new DefaultHttpClient(httpParams);
return client;
}
}
IO封装:
package com.tp.soft.io; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; public class IOUtil {
public String getJson(InputStream is){
String jsonData = "";
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String resData = "";
try {
while((resData=br.readLine())!=null){
jsonData += resData;
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
br.close();
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonData;
}
}
Constant类:
package com.tp.soft.util;
public class Constant {
public final static String ENCODING = "UTF-8";
public final static String SERVER_PATH = "http://xxx.xxx.xxx.xxx:8081/wsTest1/ws/rest/";
public final static String LOGIN_METHOD = "login";
public final static String LOGINURL = SERVER_PATH + "loginService/" + LOGIN_METHOD;
}
服务器用的是rest版的webservice
代码:
package com.tp.soft.web.ws.impl; import java.util.HashMap;
import java.util.Map; import javax.annotation.Resource;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException; import com.tp.soft.web.common.entity.Result;
import com.tp.soft.web.common.exception.BaseServiceException;
import com.tp.soft.web.common.util.Constant;
import com.tp.soft.web.dao.LoginDao;
import com.tp.soft.web.entity.po.AuUser;
import com.tp.soft.web.entity.vo.AuUserVo;
import com.tp.soft.web.ws.LoginService; @Path("/loginService")
public class LoginServiceImpl implements LoginService{ private static final Logger LOG = Logger.getLogger(LoginServiceImpl.class); @Resource(name="loginDao")
private LoginDao loginDao; @POST
@Path(value="/login")
@Produces(MediaType.APPLICATION_JSON)
public Result doLogin(@FormParam(value="username") String username, @FormParam(value="password") String password) {
Result result = new Result();
AuUserVo auUserVo = new AuUserVo();
auUserVo.setLogin_name(username);
AuUser auUser;
try{
auUser = loginDao.findUser(auUserVo);
}catch (DataAccessException e) {
LOG.error("【ibatis】登录异常", e);
throw new BaseServiceException(e.getLocalizedMessage());
} if(null == auUser){
result.setErrMsg(Constant.LOGIN_NAME_ERROR);
}else if(!password.equals(auUser.getLogin_pwd())){
result.setErrMsg(Constant.LOGIN_PWD_ERROR);
}else{
result.setSuccess(true);
Map<String, Object> map = new HashMap<String, Object>();
map.put("user", auUser);
result.setData(map);
} return result;
} }
dao里面就是ibatis调用数据库 这边就不贴了
android线程登录的更多相关文章
- 优化 Android 线程和后台任务开发
在 Android 开发中,你不应该做任何阻碍主线程的事情.但这究竟意味着什么呢?在这次海湾 Android 开发者大会讲座中,Ari Lacenski 认为对于长时间运行或潜在的复杂任务要特别小心. ...
- Android线程管理之ThreadLocal理解及应用场景
前言: 最近在学习总结Android的动画效果,当学到Android属性动画的时候大致看了下源代码,里面的AnimationHandler存取使用了ThreadLocal,激起了我很大的好奇心以及兴趣 ...
- Android线程管理之Thread使用总结
前言 最近在一直准备总结一下Android上的线程管理,今天先来总结一下Thread使用. 线程管理相关文章地址: Android线程管理之Thread使用总结 Android线程管理之Executo ...
- Android线程管理之ExecutorService线程池
前言: 上篇学习了线程Thread的使用,今天来学习一下线程池ExecutorService. 线程管理相关文章地址: Android线程管理之Thread使用总结 Android线程管理之Execu ...
- Android线程管理之ThreadPoolExecutor自定义线程池
前言: 上篇主要介绍了使用线程池的好处以及ExecutorService接口,然后学习了通过Executors工厂类生成满足不同需求的简单线程池,但是有时候我们需要相对复杂的线程池的时候就需要我们自己 ...
- Android线程管理之AsyncTask异步任务
前言: 前面几篇文章主要学习了线程以及线程池的创建与使用,今天来学习一下AsyncTask异步任务,学习下AsyncTask到底解决了什么问题?然而它有什么弊端?正所谓知己知彼百战百胜嘛! 线程管理相 ...
- Android线程之主线程向子线程发送消息
和大家一起探讨Android线程已经有些日子了,谈的最多的就是如何把子线程中的数据发送给主线程进行处理,进行UI界面的更新,为什么要这样,请查阅之前的随笔.本篇我们就来讨论一下关于主线程向子线程如何发 ...
- Android之登录时密码的保护
在很多的Android项目中都需要用户登录.注册.这样的话在开发中做好保护用户密码的工作就显得尤为重要.这里我把自己的密码保护方法记录下来. 这是我建了一个保存密码的文件,以便于检查自己保存密码或者上 ...
- Android实现登录
登录界面布局文件 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android ...
随机推荐
- PAT复杂度_最大子列和问题、最大子列和变种
01-复杂度1. 最大子列和问题 给定K个整数组成的序列{ N1, N2, ..., NK },“连续子列”被定义为{ Ni, Ni+1, ..., Nj },其中 1 <= i <= j ...
- WPF显示Html
1.添加引用 WindowsFormsIntegration.dll System.Windows.Forms.dll 2.界面内容 <UserControl x:Class="HKD ...
- struts2:字段校验和非字段校验代码示例
一.为什么要使用struts2的validate验证框架 :使用struts2的验证框架,能够提高客户端提交的数据的安全性.通过验证,确保保存进数据库的信息是正确的 二.使用struts2的valid ...
- 2-MySQL数据库编码uft-8
mysql> show variables like 'character%'; mysql> show variables like 'collation%'; mysql> st ...
- 数据库中老师学生家长表添加自动同意好友自动(AgreeAddingFriend ),默认为True
数据库中老师学生家长表添加自动同意好友自动(AgreeAddingFriend ),默认为True alter table Sys_User add AgreeAddingFriend bit alt ...
- Elasticsearch 聚合
桶(bucket)聚合 满足条件的结果集合.桶可以嵌套 标(metric)聚合 满足条件的结果集合的一些指标.如count,max等.
- Evolution项目(1)
Evolution项目是基于NFine修改的项目 主要改动为: 支持了.net core 1.0 支持了 EF core 1.0 支持数据库自动创建及Demo数据自动灌入 修改了授权方式 新增加了一个 ...
- 查看Android应用的package name和activity name方面
使用android自动化测试工具monkeyrunner启动应用时,需要填写被测程序的包名和启动的Activity,以下有两种查看应用包名package和入口activity名称的方法:方法一:使用a ...
- VB.NET中Form窗体运行时,按F1进入全屏状态
1.在KeyDown事件中添加: If e.KeyValue = 112 Then Me.WindowState = FormWindowState.Maximized End If 注:1.其中11 ...
- Swift语言之类型方法
Swift语言有很多特性,其中之一就是类型方法,相对于其他比较流行的编程语言(C#.Java),在Swift中类型方法最大的特征在于它的可继承性,我们举个例子说明: 俗话说,龙生龙凤生凤老鼠生儿会打洞 ...