android線程登入,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 = 0; 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 = 2; }else{ loginState = 1; } } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } }else{ loginState = 0; } } 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 == 0){ setMsg("isNetErr", true); }else if(status == 1){ setMsg("isNetErr", false); }else if(status == 2){ 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, 1000); /* 連線逾時 */ HttpConnectionParams.setConnectionTimeout(httpParams, 3000);// 佈建要求逾時3秒鐘 /* 請求逾時 */ HttpConnectionParams.setSoTimeout(httpParams, 3000);// 設定等待資料逾時時間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啟動線程和JAVA一樣有兩種方式,一種是直接Thread類的start方法,也就是一般寫一個自己的類來繼承Thread類。另外一種方式其實和這個差不多啊! 那就是Runnable介面,然後把Runnable的子類對象傳遞給Thread類再建立Thread對象.總之都是需要建立Thread對象,然後調用Thread類的start方法啟動線程。區別就是,一個是直接建立Thread對象,另外一個是需要implement了Runnable介面對象作為建立Thread對象的參數。Runnable其實我們稱為線程任務。
第一種方式一般是這樣用:
Class MyThread extends Thread{
public void run(){
//你要實現的代碼
}
}
在主線程中啟動這個線程:
public class Test{
public static void main(String[] args){
new MyThread().start();//啟動了我們的線程了
}
}
2,第二種方式一般是這樣用:
public class MyRunnable implements Runnable{
public void run(){
//你需要實現的代碼
}
}
在主線程中啟動這個線程:
public class Test{
public static void main(String[] args){
Thread t=new Thread(new MyRunnable());//這裡比第一種建立線程對象多了個任務對象
t.start();
}
}
這裡我想說的是可能你問這個問題是接觸到了Android中的Handler概念:
其實Handler並不是開闢新線程的概念,Android主要的考慮到更新介面的問題,一般情況下,更新介面(Activity)都是在主線程中更新的,這樣就遇到了一個問題,比方說:在下載檔案時候我們需要進度條顯示下載進度,介面需要更新(資料是不斷變的,也就是下載的大小是不斷變的,要是直接在主線程中更新,就會造成程式的堵塞,程式很容易崩潰,通常這樣連網耗時的工作需要開闢另外一個線程的,這樣就不會影響主程式了),好了,到這裡連網操作一般都需要開闢新線程了吧。。
接下來就來說Handler了,剛剛我說了Handler不是開闢新線程,在我看來,Handler更像是主線程的秘書,是一個觸發器,負責管理從子線程中得到更新的資料,然後在主線程中更新介面。簡單說下進度條的那個:
下載了多少的資料都是在子線程中得到的,在子線程中通過Handler的sendMessage()方法發送得到的下載的資料,當你調用了sendMessage方法後,Handler就會回調(也就是自動調用)Handler中的 HandlerMessage方法。
我很認真寫了,希望分給我! 要是還有不懂的,可以追問,總之Handler不是開闢線程,開闢線程的方式就和JAVA一樣的! 千萬不要被Android中的Handler混淆。
android線程與hander問題
getHtmlDate(1);使用這個方法,傳給一個值1
但從你貼的getHtmlDate函數來看,這個1值(就是arg0這個形參)根本在函數中沒有被使用到。
getHtmlDate,就是開個線程,往某個URL發個post請求,請求成功就向主線程的handler發個what=0的message,異常就發what=1的message。
從上面代碼看,getHtmlDate要不要參數無所謂。