首發地址:
android注冊 登錄+修改帳號密碼+添加資料+給指定帳號充值 .....
http://www.eoeandroid.com/thread-225709-1-1.html
仿UCWEB界面源碼!
http://www.eoeandroid.com/thread-225509-1-1.html
最近公司讓寫個android注冊 登錄 修改帳號密碼 添加資料 給新注冊用戶充值DEMO 現在功能都已經OK 目前只剩下一些小細節 現在我就把源碼發布出來 給一些需要的人參考,在這里重點只講怎么去請求服務器 和服務器返回的一些什么東西給我們 我們如何拿到 如何處理
有圖有真相(嘎嘎):
關於接口的類:
public class UserDataServiceHelper { /** 時間戳 */ static long serial = new Date().getTime(); /** KEY */ static String key = "后台人員會給你個密鑰"; /** 網站地址 */ private static final String HOST_IP = "你的請求地址"; /** 請求服務器 S1,S2,S3等 */ static String server = "s1"; /** 返回碼 1=成功 */ public static String results = null; /** 登錄UID */ public static String LoginUid = null; /** 注冊UID */ public static String RegisterUid = null; /** 快速注冊根據返回得到用戶名 */ public static String FastUserName = null; /** 快速注冊根據返回得到密碼 */ public static String FastPassWord = null; /** 快速注冊根據返回UID */ public static String Uid = null; /** 充值請求地址*/ private static final String HOST_IP_CREDIT = "你的充值請求地址"; // 注冊 public static boolean Register(Context context, String action, String username, String password, String from) { Log.i("TAG", "得到的" + context + action + username + password + from); try { HttpClient httpClient = new DefaultHttpClient(); // 請求超時 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); // 讀取超時 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); StringBuilder uri = new StringBuilder(); uri.append(HOST_IP + "XXXXXX" + "?" + "action=" + action); uri.append("&username="); uri.append(username); uri.append("&password="); uri.append(password); uri.append("&from="); uri.append(from); uri.append("&server="); uri.append(server); uri.append("&apitime="); uri.append(serial); uri.append("&key="); uri.append(getMD5Str(serial + key)); Log.i("TAG", "請求地址:" + uri.toString()); HttpPost httpPost = new HttpPost(uri.toString()); HttpResponse httpResponse = httpClient.execute(httpPost); String jsonforString = null; String result = null; String result2 = null; String result3 = null; String result4 = null; String result5 = null; String result6 = null; String result7 = null; // 返回json報文 if (httpResponse.getStatusLine().getStatusCode() == 200) { jsonforString = EntityUtils.toString(httpResponse.getEntity()); JSONObject jsonObject = new JSONObject(jsonforString); Log.i("TAG", "JSONObject對象=" + jsonforString); result = jsonObject.getString("result"); result2 = jsonObject.getString("msg"); Log.i("TAG", "result2:返回的錯誤信息"+result2); Log.i("TAG", "成功還是失敗返回" + result); if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } if (result.equalsIgnoreCase("1")) { return true; } else { return false; } } } catch (ConnectException e) { Toast.makeText(context, "網絡連接異常", Toast.LENGTH_LONG).show(); } catch (SocketTimeoutException e) { Toast.makeText(context, "連接超時", Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } return false; } // 登錄 public static boolean logins(Context context, String action, String username, String password, String from) { Log.i("TAG", "得到的" + context + action + username + password); try { HttpClient httpClient = new DefaultHttpClient(); // 請求超時 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); // 讀取超時 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); StringBuilder uri = new StringBuilder(); uri.append(HOST_IP + "XXXXXXXX" + "?" + "action=" + action); uri.append("&username="); uri.append(username); uri.append("&password="); uri.append(password); uri.append("&from="); uri.append(from); uri.append("&server="); uri.append(server); uri.append("&apitime="); uri.append(serial); uri.append("&key="); uri.append(getMD5Str(serial + key)); Log.i("TAG", "請求地址:" + uri.toString()); HttpPost httpPost = new HttpPost(uri.toString()); HttpResponse httpResponse = httpClient.execute(httpPost); String jsonforString = null; String result = null; String login = null; // 返回json報文 if (httpResponse.getStatusLine().getStatusCode() == 200) { jsonforString = EntityUtils.toString(httpResponse.getEntity()); JSONObject jsonObject = new JSONObject(jsonforString); Log.i("TAG", "JSONObject對象=" + jsonforString); result = jsonObject.getString("result"); login = jsonObject.getString("uid"); Log.i("TAG", "成功還是失敗返回" + result); if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } if (result.equalsIgnoreCase("1")) { Log.i("TAG", "服務器返回碼" + result); results = result; LoginUid = login; return true; } else { return false; } } } catch (ConnectException e) { Toast.makeText(context, "網絡連接異常", Toast.LENGTH_LONG).show(); } catch (SocketTimeoutException e) { Toast.makeText(context, "連接超時", Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } return false; } // 快速注冊 public static boolean fast(Context context, String action, String from) { try { HttpClient httpClient = new DefaultHttpClient(); // 請求超時 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); // 讀取超時 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); StringBuilder uri = new StringBuilder(); uri.append(HOST_IP + "XXXXXXXX" + "?" + "action=" + action); uri.append("&from="); uri.append(from); uri.append("&server="); uri.append(server); uri.append("&apitime="); uri.append(serial); uri.append("&key="); uri.append(getMD5Str(serial + key)); Log.i("TAG", "快速注冊請求地址:" + uri.toString()); HttpPost httpPost = new HttpPost(uri.toString()); HttpResponse httpResponse = httpClient.execute(httpPost); String jsonforString = null; String result = null; String UserNames = null; String PassWords = null; String UserId = null; // 返回json報文 if (httpResponse.getStatusLine().getStatusCode() == 200) { jsonforString = EntityUtils.toString(httpResponse.getEntity()); JSONObject jsonObject = new JSONObject(jsonforString); Log.i("TAG", "JSONObject對象=" + jsonforString); result = jsonObject.getString("result"); Log.i("TAG", "快速注冊成功還是失敗返回碼" + result); UserNames = jsonObject.getString("username"); PassWords = jsonObject.getString("password"); Log.i("TAG", "快速注冊成功返回的密碼" + PassWords); Log.i("TAG", "快速注冊成功返回用戶名" + UserNames); UserId = jsonObject.getString("uid"); if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } if (result.equalsIgnoreCase("1")) { Log.i("TAG", "快速注冊服務器返回碼" + result); results = result; FastUserName = UserNames; FastPassWord = PassWords; Uid = UserId; return true; } else { return false; } } } catch (ConnectException e) { Toast.makeText(context, "網絡連接異常", Toast.LENGTH_LONG).show(); } catch (SocketTimeoutException e) { Toast.makeText(context, "連接超時", Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } return false; } // 修改帳號 public static boolean updateData(Context context, String action, String uid, String username, String password, String newname, String newpass) { try { HttpClient httpClient = new DefaultHttpClient(); // 請求超時 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); // 讀取超時 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); StringBuilder uri = new StringBuilder(); uri.append(HOST_IP + "XXXXXXXXX" + "?" + "action=" + action); uri.append("&uid="); uri.append(uid); uri.append("&username="); uri.append(username); uri.append("&password="); uri.append(password); uri.append("&newname="); uri.append(newname); uri.append("&newpass="); uri.append(newpass); uri.append("&server="); uri.append(server); uri.append("&apitime="); uri.append(serial); uri.append("&key="); uri.append(getMD5Str(serial + key)); Log.i("TAG", "提交更新:" + uri.toString()); HttpPost httpPost = new HttpPost(uri.toString()); HttpResponse httpResponse = httpClient.execute(httpPost); String jsonforString = null; String result = null; String UserNames = null; String PassWords = null; String UserId = null; // 返回json報文 if (httpResponse.getStatusLine().getStatusCode() == 200) { jsonforString = EntityUtils.toString(httpResponse.getEntity()); JSONObject jsonObject = new JSONObject(jsonforString); // Log.i("TAG", "JSONObject對象=" + jsonforString); result = jsonObject.getString("result"); Log.i("TAG", "提交更新返回碼" + result); // UserNames = jsonObject.getString("username"); // PassWords = jsonObject.getString("password"); // Log.i("TAG", "快速注冊成功返回的密碼" + PassWords); // Log.i("TAG", "快速注冊成功返回用戶名" + UserNames); UserId = jsonObject.getString("uid"); if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } if (result.equalsIgnoreCase("1")) { Log.i("TAG", "提交更新" + result); // results = result; // FastUserName = UserNames; // FastPassWord = PassWords; // Uid = UserId; return true; } else { return false; } } } catch (ConnectException e) { Toast.makeText(context, "網絡連接異常", Toast.LENGTH_LONG).show(); } catch (SocketTimeoutException e) { Toast.makeText(context, "連接超時", Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } return false; } // MD5 public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray<i>).length() == 1) { md5StrBuff.append("0").append( Integer.toHexString(0xFF & byteArray<i>)); } else { md5StrBuff.append(Integer.toHexString(0xFF & byteArray<i>)); } } return md5StrBuff.toString(); } }
首先我們先看一下請求服務器的類 如何寫的
我們首先看注冊那邊返回的JSON都是什么內容吧(一會我會講到如何抓到result>1的錯誤信息,然后返回給activity顯示出來) 一般你們公司都會有個后台給你們寫個接口文檔扔給你 讓你去做的
{ “result”: 1, “uid”:22771,”msg”:””} result=1 注冊成功, uid為玩家uid, msg為空 result>1時注冊失敗, 此時返回的 uid=0 result=2: msg:用戶名格式不對 result=3: msg:此用戶名已經被注冊 result=4: msg:密碼格式不對(長度不是6-16位或者包含了其他字符,比如中文標點之類) result=5: msg:廣告來源為空 from 的值不允許為空 result=6: msg:系統維護,此時不允許注冊 result>6 時為其他錯誤, msg會返回錯誤的具體原因
我們在注冊頁面去請求服務器:
在我的工程:Register類
boolean flag ;//條件成立跳轉到登陸界面 /** 請求服務器 */ if (userName != null || password != null || from != null) { flag = UserDataServiceHelper.Register(context, "reg", userName, password, from); if(flag){ Intent intent = new Intent(); intent.putExtra("name", userName); intent.putExtra("pw", password); intent.putExtra("fm",from); intent.setClass(Register.this, Login.class); startActivity(intent); }else { Log.i("TAG", "不成立"); } Log.i("TAG", "請求服務器" + userName + password + from); }
傳的參數里面 第一個就是context 第二個就是一個注冊的參數(你們后台都會有自己弄一個參數來區分的),第三個參數就是你的名字 第4個參數就是你的密碼 第五個參數其實就是一個渠道的意思(從那個渠道過來注冊的,比如你從googlePlay注冊的 這里隨便定義一個參數 讓你們的老大知道這個從googlePlay下載注冊的,現在產品都這樣搞的)
如果注冊接口成功返回true 那么flag就會是true(默認是false嘛) 就去執行Intent,然后putExtra 把需要的東西傳值到登錄界面
登錄界面會做什么事呢? 接着上面的問題 看下面的代碼:
/** 初始化注冊VIEW組件 */ private void findViewById() { view_userName = (EditText) findViewById(R.id.loginUserNameEdit); view_password = (EditText) findViewById(R.id.loginPasswordEdit); view_rememberMe = (CheckBox) findViewById(R.id.loginRememberMeCheckBox); view_loginSubmit = (Button) findViewById(R.id.loginSubmit); view_loginRegister = (Button) findViewById(R.id.loginRegister); view_fast = (TextView) findViewById(R.id.fast); /** 注冊成功后傳過來用戶名和密碼,顯示在登錄界面 */ if (!flag) { Intent intent = getIntent(); userName = intent.getStringExtra("name"); password = intent.getStringExtra("pw"); from = intent.getStringExtra("fm"); view_rememberMe.setChecked(false);//小BUG view_userName.setText(userName); view_password.setText(password); } }
登錄界面就會用getStringExtra方法把剛剛從注冊傳過來的值 這里是根據Key,value 我們只要得到這個key("name")就OK了。
然后我們在用setText 顯示在editText上!
view_userName.setText(userName);
view_password.setText(password);
然后我們在點擊登錄的時候看代碼 如何把剛剛從注冊傳過來的值在去傳到登錄接口 其實在這里很簡單 在賦值給的string就OK了 賦值好后然后在把賦值的值傳到登錄接口 看例子:
/** 登錄Button Listener */ private OnClickListener submitListener = new OnClickListener() { @Override public void onClick(View v) { Log.i("TAG", "submitListener"); proDialog = ProgressDialog.show(Login.this, "連接中..", "連接中..請稍后....", true, true); // 開啟一個線程進行登錄驗證,主要是用戶失敗成功可以直接通過startAcitivity(Intent)轉向 Thread loginThread = new Thread(new LoginFailureHandler()); loginThread.start();// 開啟 } };
// 另起一個線程登錄 class LoginFailureHandler implements Runnable { @Override public void run() { userName = view_userName.getText().toString(); Log.i("TAG", "userName LoginFailureHandler" + userName); password = view_password.getText().toString(); Log.i("TAG", "password LoginFailureHandler" + password); /** 請求服務器 */ if (userName != null || password != null) { boolean loginState = UserDataServiceHelper.logins(context, "login", userName, password, from); Log.i("TAG", "登錄返回條件" + loginState); // 登錄成功 if (loginState) { String LoginUerId = UserDataService.LoginUid; // 需要傳輸數據到登陸后的界面, Intent intent = new Intent(); intent.setClass(Login.this, IndexPage.class); Bundle bundle = new Bundle(); bundle.putString("LOGIN_USERNAME", userName); bundle.putString("LOGIN_PASSWORD", password); bundle.putString("LOGIN_ID", LoginUerId); intent.putExtras(bundle); // 轉向登陸后的頁面 startActivity(intent); // /** 得到請求服務器返回碼 */ String loginStateInt = UserDataService.results; int Less = Integer.valueOf(loginStateInt); // 轉換成整形 Log.i("TAG", "登錄后的返回碼:" + Less); if (Less == 1) { StatusCode = true; } // 登錄成功記住帳號密碼 if (StatusCode) { if (isRememberMe()) { saveSharePreferences(true, true); } else { saveSharePreferences(true, false); } } else { // 如果不是網絡錯誤 if (!isNetError) { clearSharePassword(); clearShareName(); } } if (!view_rememberMe.isChecked()) { clearSharePassword(); clearShareName(); } proDialog.dismiss(); } else { // 通過調用handler來通知UI主線程更新UI, Log.i("TAG", "連接失敗"); Message message = new Message(); Bundle bundle = new Bundle(); bundle.putBoolean("isNetError", isNetError); message.setData(bundle); loginHandler.sendMessage(message); } } } }
登錄后 我們就會看到一個登錄成功的頁面,下面有4個按鈕 修改帳號,添加資料,從設密碼
那么修改帳號的流程 還是跟上面登錄注冊一樣 把所有的值用putExtra方法傳過來 然后在修改帳號頁面getStringExtra在得到("name",passwor)等 ,在從新聲明一個string類型 在賦值 在去請求 修改帳號密碼接口
添加資料也就是去請求地址 然后里面需要傳什么東西 就傳什么過去。
從設置也是和上面的流程 putExtra-----getStringExtra("name",passwor)等 在從新聲明一個string類型 在賦值 在去請求
其實注冊 登錄 修改帳號密碼 和添加資料 都是很簡單的 無非就是putExtra getStringExtra 聲明 賦值 請求 返回信息 顯示
備注:
附件里面我把接口那部分已經刪掉了 你們可以看上面我寫的請求服務器的類 根據自己的業務需求來添加和刪除 請求服務器類寫的一個不好的地方就是 每個方法都加了static 呵呵 這個原因主要是 我寫了一個方法 然后剩下的接口我就復制上面的 然后改改。