android 註冊,登錄 + 修改帳號密碼 + 添加資料 + 給指定帳號充值

博文轉自:http://blog.csdn.net/zxciop110/article/details/8151678

最近公司讓寫個android註冊 登錄 修改帳號密碼 添加資料 給新註冊用戶充值DEMO  現在功能都已經OK  目前只剩下一些小細節  現在我就把源碼發佈出來 給一些需要的人蔘考,在這裏重點只講怎麼去請求服務器 和服務器返回的一些什麼東西給我們 我們如何拿到 如何處理最後的時候我會把整個項目打包


都是本人原創 只是我提前在EOE論壇發佈了。


有圖有真相:
device-2012-11-05-212526.png


device-2012-11-05-212729.png


device-2012-11-05-212758.png


device-2012-11-05-212923.png


device-2012-11-05-212938.png



device-2012-11-05-212948.png

首先我們先看一下請求服務器的類 如何寫的 可結合我上一篇:
http://www.eoeandroid.com/thread-212252-1-1.html   
這裏就完善上一篇的內容:


我們首先看註冊那邊返回的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  呵呵   這個原因主要是  我寫了一個方法  然後剩下的接口我就複製上面的 然後改改。


    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();  
        }  
       
       
    }  
    </i></i></i>  




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章