Handler&Looper&Message&Runnable多线程
看过好多资料,原来对Handler&Message&looper&Runnable多线程一知半解,现在写了个demo‘,认真分析理解了一下,帮助大家把这几个知识点连贯的串一下,希望对大家有所帮助。
自Android2.3以后,谷歌官方规定,耗时的任务不能在主线程出现,会严重影响用户的体验,其实就算谷歌不提出,有经验的程序员也不会把耗时任务放在主线程的,这样会给用户造成一个假死的现象,所以一引入了Handler。Looper虽然大家看不到,但是却有至关重要的作用http://blog.csdn.net/qq_23195583/article/details/44221401
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
// 登录
case R.id.login_btn_login:
//主线程,在looper中进行循环执行
mDialog = new ProgressDialog(LoginDemoActivity.this);
mDialog.setTitle("登陆");
mDialog.setMessage("正在登陆服务器,请稍后...");
mDialog.show();
//子线程,开始执行LoginThread线程类
Thread loginThread = new Thread(new LoginThread());
loginThread.start();
break;
// 注册
case R.id.login_btn_zhuce:
Intent intent = new Intent();
intent.setClass(LoginDemoActivity.this, RegisterActivity.class);
startActivity(intent);
default:
break;
}
}
// LoginThread线程类
class LoginThread implements Runnable {
@Override
public void run() {
String username = inputUsername.getText().toString();
String password = inputPassword.getText().toString();
boolean checkstatus = sp.getBoolean("checkstatus", false);
if (checkstatus) {
// 获取已经存在的用户名和密码
String realUsername = sp.getString("username", "");
String realPassword = sp.getString("password", "");
if ((!realUsername.equals("")) && !(realUsername == null)
|| (!realPassword.equals(""))
|| !(realPassword == null)) {
if (username.equals(realUsername)
&& password.equals(realPassword)) {
username = inputUsername.getText().toString();
password = inputPassword.getText().toString();
}
}
} else {
password = password;
}
// URL合法,但是这一步并不验证密码是否正确
boolean loginValidate = false;
try {
loginValidate = loginServer(username, password);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//下面代码将message放入looper消息队列中,一个looper可以有多个message队列,但是一个message只能对应一个looper
Message msg = handler.obtainMessage();
if (loginValidate) {
//根据返回不同的结果赋给msg不同的值
if (responseMsg.equals("0")) {
msg.what = 0;
handler.sendMessage(msg);
} else {
msg.what = 1;
handler.sendMessage(msg);
}
} else {
msg.what = 2;
handler.sendMessage(msg);
}
}
}
// Handler,根据不同的message的值,执行不同的请求
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
mDialog.cancel();
Toast.makeText(getApplicationContext(), "登录成功!",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setClass(LoginDemoActivity.this, MainActivity.class);
startActivity(intent);
finish();
break;
case 1:
mDialog.cancel();
Toast.makeText(getApplicationContext(), "密码错误",
Toast.LENGTH_SHORT).show();
break;
case 2:
mDialog.cancel();
Toast.makeText(getApplicationContext(), "URL验证失败",
Toast.LENGTH_SHORT).show();
break;
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。