Android實現註冊登錄頭像上傳等功能常規開發(Android端,服務器端開發實例)

 

Android實現註冊登錄頭像上傳等功能常規開發(Android端,服務器端開發實例)

標籤: 註冊登錄Android開發servlet
2017-04-18 20:34  454人閱讀  評論(1)  收藏  舉報
  分類:
   

目錄(?)[+]

時隔半年再次敲動鍵盤,發現時間過得真心快。原本自己該乾的事情被瑣碎事情給耽擱了,現在想想該重新振奮起來好好努力。閒話到此,今天給大家帶來的教程是常規化也是常見的登錄註冊上傳頭像等操作,本篇也是從項目中挑出部分,項目是真實測試的,完全能實現如上操作,所以各位不用擔心,由於時間原因,就不連接服務器測試了,本篇文章也只是演示下過程。包括了客戶端和服務器的部分程序,當然了該篇博客僅限學習,下面進入正文。下面是項目的註冊登錄部分在模擬器上的演示:


在開始講解咱們的項目之前咱們先整理下思路。在學習本篇文章前請了解並學習下列相關知識:

  • okhttp網絡請求庫最新版本的使用方法(建議去github下載相應的okhttp工具類)
  • Mysql數據庫進行數據存儲
  • servlet相關知識(請參考 超詳細servlet+jdbc+html+css實現後臺管理登陸)
  • Base64圖片編碼
  • Tomcat服務器實現虛擬映射路徑設置(在本篇文章中將圖片保存在服務器的虛擬映射路徑中)

注意:本篇文章可能不能完全把代碼完全註釋講解,所以敬請大家有點耐心。

客戶端:

  1. 編寫註冊界面的xml佈局文件
  2. 實現註冊界面的邏輯實現
  3. 編寫登錄界面的XML佈局文件
  4. 實現登錄界面的邏輯實現  
首先我們看到客戶端的整體的結構圖:


註冊界面佈局:wyt_register.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     android:id="@+id/register"  
  5.     android:orientation="vertical"  
  6.     android:layout_width="match_parent"  
  7.     android:layout_height="match_parent"  
  8.     android:background="#f5f5f5"  
  9.     >  
  10.     <LinearLayout  
  11.         android:layout_width="match_parent"  
  12.         android:layout_height="wrap_content"  
  13.         android:orientation="vertical">  
  14.         <com.mero.wyt_register.widget.CustomTitleBar  
  15.             android:layout_width="match_parent"  
  16.             android:layout_height="80dp"  
  17.             app:text="用戶註冊"  
  18.             app:background_color="@color/mediumturquoise"  
  19.             />  
  20.         <LinearLayout  
  21.             android:layout_width="match_parent"  
  22.             android:layout_height="150dp"  
  23.             android:orientation="vertical"  
  24.             android:background="@color/mediumturquoise">  
  25.             <RelativeLayout  
  26.                 android:layout_width="match_parent"  
  27.                 android:layout_height="match_parent">  
  28.                 <ImageView  
  29.                     android:id="@+id/img_upload_img"  
  30.                     android:layout_width="100dp"  
  31.                     android:layout_height="100dp"  
  32.                     android:layout_centerHorizontal="true"  
  33.                     android:src="@drawable/menu_item_theme"/>  
  34.                 <TextView  
  35.                     android:id="@+id/tx_upload_img"  
  36.                     android:layout_below="@id/img_upload_img"  
  37.                     android:layout_width="wrap_content"  
  38.                     android:layout_height="wrap_content"  
  39.                     android:text="上傳頭像"  
  40.                     android:layout_centerHorizontal="true"  
  41.                     android:textSize="15sp"  
  42.                     android:gravity="fill_vertical"  
  43.                     android:textColor="#fff"/>  
  44.             </RelativeLayout>  
  45.         </LinearLayout>  
  46.   
  47.     </LinearLayout>  
  48.   
  49.     <LinearLayout  
  50.         android:layout_width="match_parent"  
  51.         android:layout_height="100dp"  
  52.         android:orientation="vertical"  
  53.         android:background="#FFF">  
  54.         <LinearLayout  
  55.             android:layout_width="match_parent"  
  56.             android:layout_height="50dp"  
  57.             android:orientation="horizontal">  
  58.             <ImageView  
  59.                 android:id="@+id/img_register_account"  
  60.                 android:layout_width="32dp"  
  61.                 android:layout_height="32dp"  
  62.                 android:src="@drawable/account"  
  63.                 android:layout_marginLeft="10dp"  
  64.                 android:layout_gravity="center_vertical"/>  
  65.             <EditText  
  66.                 android:id="@+id/edt_register_account"  
  67.                 android:layout_width="match_parent"  
  68.                 android:layout_height="50dp"  
  69.                 android:hint="賬號"  
  70.                 android:textColorHighlight="#77000000"  
  71.                 android:textColor="#000000"  
  72.                 android:maxLines="1"  
  73.                 android:background="@null"  
  74.                 android:gravity="center_vertical"  
  75.                 android:paddingLeft="15dp"  
  76.                 android:textSize="15sp"  
  77.                 android:textColorHint="#77000000"  
  78.                 />  
  79.         </LinearLayout>  
  80.         <TextView  
  81.             android:layout_width="match_parent"  
  82.             android:layout_height="1dp"  
  83.             android:background="#f5f5f5"/>  
  84.         <LinearLayout  
  85.             android:layout_width="match_parent"  
  86.             android:layout_height="match_parent"  
  87.             android:orientation="horizontal"  
  88.             android:background="#FFF"  
  89.             android:baselineAligned="false">  
  90.             <ImageView  
  91.                 android:id="@+id/img_register_pwd"  
  92.                 android:layout_width="32dp"  
  93.                 android:layout_height="32dp"  
  94.                 android:layout_marginLeft="10dp"  
  95.                 android:src="@drawable/pwd"  
  96.                 android:layout_gravity="center_vertical"/>  
  97.             <EditText  
  98.                 android:id="@+id/edt_register_pwd"  
  99.                 android:layout_width="match_parent"  
  100.                 android:layout_height="match_parent"  
  101.                 android:hint="密碼"  
  102.                 android:inputType="textPassword"  
  103.                 android:maxLines="1"  
  104.                 android:textSize="15sp"  
  105.                 android:textColorHighlight="#77000000"  
  106.                 android:textColor="#000000"  
  107.                 android:background="@null"  
  108.                 android:paddingLeft="15sp"  
  109.                 android:textColorHint="#77000000"  
  110.                 android:layout_weight="1" />  
  111.         </LinearLayout>  
  112.     </LinearLayout>  
  113.     <RelativeLayout  
  114.         android:layout_width="match_parent"  
  115.         android:layout_height="50dp"  
  116.         android:layout_marginTop="20dp">  
  117.         <com.mero.wyt_register.widget.RoundButton  
  118.             android:id="@+id/btn_to_register"  
  119.             android:layout_width="300dp"  
  120.             android:layout_height="50dp"  
  121.             android:text="註冊"  
  122.             android:textColor="#FFF"  
  123.             android:textStyle="bold"  
  124.             android:textSize="15sp"  
  125.             android:gravity="center"  
  126.             android:layout_centerInParent="true"  
  127.             app:btnCornerRadius="10dp"  
  128.             app:btnSolidColor="@color/mediumturquoise"  
  129.             app:btnPressedRatio="1.5"  
  130.             />  
  131.     </RelativeLayout>  
  132. </LinearLayout>  

效果如下:

登錄界面佈局wyt_login.xml:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     android:orientation="vertical"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:background="#f5f5f5"  
  8.     >  
  9.     <com.mero.wyt_register.widget.CustomTitleBar  
  10.       android:layout_width="match_parent"  
  11.       android:layout_height="80dp"  
  12.       app:text="用戶登錄"  
  13.       app:background_color="@color/mediumturquoise"  
  14.         />  
  15.   
  16.     <LinearLayout  
  17.         android:layout_width="match_parent"  
  18.         android:layout_height="100dp"  
  19.         android:orientation="vertical"  
  20.         android:background="#FFF">  
  21.         <LinearLayout  
  22.             android:layout_width="match_parent"  
  23.             android:layout_height="50dp"  
  24.             android:orientation="horizontal">  
  25.             <ImageView  
  26.                 android:id="@+id/img_login_account"  
  27.                 android:layout_width="32dp"  
  28.                 android:layout_height="32dp"  
  29.                 android:src="@drawable/account"  
  30.                 android:layout_marginLeft="10dp"  
  31.                 android:layout_gravity="center_vertical"/>  
  32.             <EditText  
  33.                 android:id="@+id/edt_login_account"  
  34.                 android:layout_width="match_parent"  
  35.                 android:layout_height="50dp"  
  36.                 android:hint="賬號"  
  37.                 android:textColorHighlight="#77000000"  
  38.                 android:textColor="#000000"  
  39.                 android:maxLines="1"  
  40.                 android:background="@null"  
  41.                 android:gravity="center_vertical"  
  42.                 android:paddingLeft="15dp"  
  43.                 android:textSize="15sp"  
  44.                 android:textColorHint="#77000000"  
  45.                 />  
  46.         </LinearLayout>  
  47.         <TextView  
  48.             android:layout_width="match_parent"  
  49.             android:layout_height="1dp"  
  50.             android:background="#f5f5f5"/>  
  51.         <LinearLayout  
  52.             android:layout_width="match_parent"  
  53.             android:layout_height="match_parent"  
  54.             android:orientation="horizontal"  
  55.             android:background="#FFF"  
  56.             android:baselineAligned="false">  
  57.             <ImageView  
  58.                 android:id="@+id/img_login_pwd"  
  59.                 android:layout_width="32dp"  
  60.                 android:layout_height="32dp"  
  61.                 android:layout_marginLeft="10dp"  
  62.                 android:src="@drawable/pwd"  
  63.                 android:layout_gravity="center_vertical"/>  
  64.             <EditText  
  65.                 android:id="@+id/edt_login_pwd"  
  66.                 android:layout_width="match_parent"  
  67.                 android:layout_height="match_parent"  
  68.                 android:inputType="textPassword"  
  69.                 android:hint="密碼"  
  70.                 android:maxLines="1"  
  71.                 android:textSize="15sp"  
  72.                 android:textColorHighlight="#77000000"  
  73.                 android:textColor="#000000"  
  74.                 android:background="@null"  
  75.                 android:paddingLeft="15sp"  
  76.                 android:textColorHint="#77000000"  
  77.                 android:layout_weight="1" />  
  78.         </LinearLayout>  
  79.     </LinearLayout>  
  80.     <RelativeLayout  
  81.         android:layout_width="match_parent"  
  82.         android:layout_height="50dp"  
  83.         android:layout_marginTop="20dp">  
  84.         <com.mero.wyt_register.widget.RoundButton  
  85.             android:id="@+id/btn_login_click_to_login"  
  86.             android:layout_width="300dp"  
  87.             android:layout_height="50dp"  
  88.             android:text="立即登錄"  
  89.             android:textColor="@color/white"  
  90.             android:textSize="15sp"  
  91.             android:gravity="center"  
  92.             android:layout_centerInParent="true"  
  93.             app:btnCornerRadius="10dp"  
  94.             app:btnSolidColor="@color/mediumturquoise"  
  95.             app:btnPressedRatio="1.5"  
  96.             />  
  97.     </RelativeLayout>  
  98.     <RelativeLayout  
  99.         android:layout_width="match_parent"  
  100.         android:layout_height="50dp">  
  101.         <TextView  
  102.             android:id="@+id/tx_login_click_to_register"  
  103.             android:layout_width="wrap_content"  
  104.             android:layout_height="match_parent"  
  105.             android:layout_alignParentRight="true"  
  106.             android:text="點擊註冊"  
  107.             android:textColor="#33aa44"  
  108.             android:textSize="15sp"  
  109.             android:textStyle="bold"  
  110.             android:paddingRight="25dp"  
  111.             android:paddingTop="25dp"  
  112.             />  
  113.     </RelativeLayout>  
  114. </LinearLayout>  

登錄界面效果如下:


接下來是我們的註冊界面的邏輯代碼:

RegisterAty.java

[java]  view plain  copy
  1. package com.mero.wyt_register.activity;  
  2.   
  3. import android.app.ProgressDialog;  
  4. import android.content.Intent;  
  5. import android.database.Cursor;  
  6. import android.graphics.Bitmap;  
  7. import android.graphics.BitmapFactory;  
  8. import android.net.Uri;  
  9. import android.os.Handler;  
  10. import android.os.Message;  
  11. import android.provider.MediaStore;  
  12. import android.text.TextUtils;  
  13. import android.view.Gravity;  
  14. import android.view.View;  
  15. import android.view.animation.AnimationSet;  
  16. import android.view.animation.TranslateAnimation;  
  17. import android.widget.EditText;  
  18. import android.widget.ImageView;  
  19. import android.widget.Toast;  
  20.   
  21. import com.mero.wyt_register.Base.BaseSwipeBackLayout;  
  22. import com.mero.wyt_register.Config;  
  23. import com.mero.wyt_register.R;  
  24. import com.mero.wyt_register.net.RegisterAction;  
  25. import com.mero.wyt_register.utils.AppUtils;  
  26. import com.mero.wyt_register.utils.Base64Utils;  
  27. import com.mero.wyt_register.utils.SDCardUtils;  
  28. import com.mero.wyt_register.widget.RoundButton;  
  29. import com.mero.wyt_register.widget.SelectPicPopupWindow;  
  30.   
  31. /** 
  32.  * Created by chenlei on 2016/11/17. 
  33.  */  
  34.   
  35. public class RegisterAty extends BaseSwipeBackLayout implements View.OnClickListener {  
  36.     private ImageView img_upload;  
  37.     private EditText edt_account = null;  
  38.     private EditText edt_pwd = null;  
  39.     private RoundButton btn_register = null;  
  40.     private static final int RESULT_OPEN_IMAGE = 1;  
  41.     private Bitmap bitmap ;//存放裁剪後的頭像  
  42.     private String fileName;//頭像名稱  
  43.     private String picturePath;//頭像路徑  
  44.     private ProgressDialog pd;//進度條  
  45.     private static final int DISMISS = 1000;//進度條消失  
  46.     private SelectPicPopupWindow selectPicPopupWindow;  
  47.     @Override  
  48.     public void initView() {  
  49.         img_upload = (ImageView) findViewById(R.id.img_upload_img);  
  50.         edt_account = (EditText) findViewById(R.id.edt_register_account);  
  51.         edt_pwd = (EditText) findViewById(R.id.edt_register_pwd);  
  52.         img_upload.setOnClickListener(this);  
  53.         btn_register = (RoundButton) findViewById(R.id.btn_to_register);  
  54.         btn_register.setOnClickListener(this);  
  55.     }  
  56.     @Override  
  57.     public void initData() {  
  58.   
  59.     }  
  60.     private final Handler handler = new Handler(){  
  61.         @Override  
  62.         public void handleMessage(Message msg) {  
  63.             if(msg.what == DISMISS){  
  64.                 pd.dismiss();  
  65.             }  
  66.         }  
  67.     };  
  68.     @Override  
  69.     public int getLayoutResourceId() {  
  70.         return R.layout.wyt_register;  
  71.     }  
  72.   
  73.     @Override  
  74.     public int getDialogIcon() {  
  75.         return 0;  
  76.     }  
  77.   
  78.     @Override  
  79.     public int setStatusBarColor() {  
  80.         return 0;  
  81.     }  
  82.   
  83.     private static final int CAMERA_REQUEST_CODE = 1;//拍照返回碼  
  84.     private static final int GALLERY_REQUEST_CODE = 2;//相冊返回碼  
  85.     @Override  
  86.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  87.         super.onActivityResult(requestCode, resultCode, data);  
  88.         //如果是拍照返回  
  89.         if(requestCode==CAMERA_REQUEST_CODE&&resultCode==RESULT_OK&&data!=null) {  
  90.             Uri uri = data.getData();  
  91.             if (uri != null) {  
  92.                 Cursor cursor = this.getContentResolver().query(uri, nullnullnullnull);  
  93.                 if (cursor.moveToFirst()) {  
  94.                     picturePath = cursor.getString(cursor.getColumnIndex("_data"));  
  95.                     fileName = getBitmapName(picturePath);  
  96.                     bitmap = AppUtils.toRoundBitmap(BitmapFactory.decodeFile(picturePath));  
  97.                     //進行裁剪  
  98.                     img_upload.setImageBitmap(bitmap);  
  99.                 }  
  100.             } else {  
  101.                 Toast.makeText(this,"保存照片失敗",Toast.LENGTH_SHORT).show();  
  102.                 return;  
  103.             }  
  104.         }  
  105.   
  106.   
  107.         //如果是相冊返回  
  108.         if(requestCode==GALLERY_REQUEST_CODE&&resultCode==RESULT_OK&&null!=data){  
  109.             Uri selectedImage = data.getData();  
  110.             String[] filePathColumn = {MediaStore.Images.Media.DATA};  
  111.   
  112.             Cursor cursor = getContentResolver().query(selectedImage,  
  113.                     filePathColumn, nullnullnull);  
  114.             cursor.moveToFirst();  
  115.             int columnIndex = cursor.getColumnIndex(filePathColumn[0]);  
  116.             picturePath = cursor.getString(columnIndex);  
  117.             fileName = getBitmapName(picturePath);  
  118.             cursor.close();  
  119.             //裁剪爲圓形頭像  
  120.             if(SDCardUtils.isSDCardEnable()){  
  121.                 bitmap = AppUtils.toRoundBitmap(BitmapFactory.decodeFile(picturePath));  
  122.                 img_upload.setImageBitmap(bitmap);//設置到圖片  
  123.             }else {  
  124.                 return;  
  125.             }  
  126.         }else {  
  127.             return;  
  128.         }  
  129.     }  
  130.     //獲取圖片的名稱  
  131.     public String getBitmapName(String picPath){  
  132.         String bitmapName="";  
  133.         String[]  s = picPath.split("/");  
  134.         bitmapName = s[s.length-1];  
  135.         return bitmapName;  
  136.     }  
  137.     @Override  
  138.     public void onClick(View v) {  
  139.         switch (v.getId()) {  
  140.             case R.id.img_upload_img:  
  141.                 //判斷是否從相冊或者調用相機實現  
  142.                 selectPicPopupWindow = new SelectPicPopupWindow(RegisterAty.thisnew View.OnClickListener() {  
  143.                     @Override  
  144.                     public void onClick(View v) {  
  145.                         selectPicPopupWindow.dismiss();  
  146.                         switch (v.getId()){  
  147.                             case R.id.btn_select_camera:  
  148.                                 //從相機拍照  
  149.                                 Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
  150.                                 startActivityForResult(i,1);  
  151.                                 break;  
  152.                             case R.id.btn_select_pic_photo_lib:  
  153.                                 //從圖庫選擇照片  
  154.                                 Intent ii = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
  155.                                 startActivityForResult(ii, RESULT_OPEN_IMAGE);  
  156.                                 break;  
  157.                         }  
  158.                     }  
  159.                 });  
  160.                 View view = RegisterAty.this.findViewById(R.id.register);  
  161.                 selectPicPopupWindow.showAtLocation(view, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,0);  
  162.                 AnimationSet animationSet = new AnimationSet(true);  
  163.                 TranslateAnimation translateAnimation = new TranslateAnimation(1,0,1,0);  
  164.                 translateAnimation.setDuration(1000);  
  165.                 animationSet.addAnimation(translateAnimation);  
  166.                 view.startAnimation(translateAnimation);  
  167.                 break;  
  168.             case R.id.btn_to_register:  
  169.                 //點擊的是註冊按鈕  
  170.                 final String wyt_account = edt_account.getText().toString();//獲取賬號  
  171.                 final String wyt_pwd = edt_pwd.getText().toString();//獲取密碼  
  172.                 if(TextUtils.isEmpty(wyt_account)){  
  173.                     Toast.makeText(RegisterAty.this,"賬號不能爲空",Toast.LENGTH_SHORT).show();  
  174.                     return;  
  175.                 }  
  176.                 if(TextUtils.isEmpty(wyt_pwd)){  
  177.                     Toast.makeText(RegisterAty.this,"密碼不能爲空",Toast.LENGTH_SHORT).show();  
  178.                     return;  
  179.                 }  
  180.                 if(wyt_account.length()>20){  
  181.                     Toast.makeText(RegisterAty.this,"您輸入的賬號過長",Toast.LENGTH_SHORT).show();  
  182.                     return;  
  183.                 }  
  184.                 if(wyt_pwd.length()>20){  
  185.                     Toast.makeText(RegisterAty.this,"您輸入的密碼過長",Toast.LENGTH_SHORT).show();  
  186.                     return;  
  187.                 }  
  188.                 pd = ProgressDialog.show(this,"溫馨提示","正在註冊...",false,true);  
  189.                 if(null!=bitmap){  
  190.                     //截取圖片後綴  
  191.   
  192.                     String base64img = Base64Utils.bitmaptoString(bitmap);  
  193.                     //進行用戶註冊  
  194.                     new RegisterAction(Config.URL, Config.KEY_REGISTER, wyt_account, wyt_pwd, base64img, new RegisterAction.ISuccessCallback() {  
  195.                         @Override  
  196.                         public void onSuccess(String response, int id) {  
  197.                             pd.setMessage("註冊成功");  
  198.                             handler.sendEmptyMessageDelayed(DISMISS,1000);  
  199.                             showActivity(RegisterAty.this,LoginAty.class);  
  200.                         }  
  201.                     }, new RegisterAction.IFailCallback() {  
  202.                         @Override  
  203.                         public void onFail(String failMsg) {  
  204.                             pd.setMessage("註冊失敗"+failMsg);  
  205.                             handler.sendEmptyMessageDelayed(DISMISS,1000);  
  206.                         }  
  207.                     });  
  208.                 }  
  209.   
  210.                 break;  
  211.             default:  
  212.                 break;  
  213.         }  
  214.     }  
  215.     private String getPicType(String picName){  
  216.         String[] s = picName.split(".");  
  217.         //數組長度  
  218.         return s[s.length-1];  
  219.     }  
  220.   
  221. }  


然後對註冊界面的網絡請求進行封裝:

RegisterAction.java

[java]  view plain  copy
  1. package com.mero.wyt_register.net;  
  2.   
  3. import android.util.Log;  
  4.   
  5. import com.mero.wyt_register.Config;  
  6. import com.zhy.http.okhttp.OkHttpUtils;  
  7. import com.zhy.http.okhttp.callback.StringCallback;  
  8.   
  9. import org.json.JSONException;  
  10. import org.json.JSONObject;  
  11.   
  12. import java.io.File;  
  13. import java.util.HashMap;  
  14. import java.util.Map;  
  15.   
  16. import okhttp3.Call;  
  17.   
  18. import static android.R.attr.action;  
  19. import static com.google.android.gms.internal.zzs.TAG;  
  20. import static com.mero.wyt_register.R.drawable.account;  
  21. import static com.zhy.http.okhttp.OkHttpUtils.post;  
  22.   
  23. /** 
  24.  * Created by chenlei on 2016/11/17. 
  25.  */  
  26.   
  27. public class RegisterAction {  
  28.     /* 
  29.     * 註冊 
  30.     * */  
  31.     public RegisterAction(String url, String action, String account, String pwd, String picBase64, final ISuccessCallback successCallback, final IFailCallback failCallback){  
  32.         OkHttpUtils  
  33.                 .post()  
  34.                 .url(url)  
  35.                 .addParams(Config.KEY_ACTION,action)  
  36.                 .addParams(Config.KEY_ACCOUNT,account)  
  37.                 .addParams(Config.KEY_PWD,pwd)  
  38.                 .addParams(Config.KEY_USER_ICON,picBase64)  
  39.                 .build()  
  40.                 .execute(new StringCallback() {  
  41.                     @Override  
  42.                     public void onError(Call call, Exception e, int id) {  
  43.                             if(null!=failCallback){  
  44.                                 Log.e(TAG,"註冊失敗"+e.getMessage());  
  45.                                 failCallback.onFail(e.getMessage());  
  46.                             }  
  47.                     }  
  48.   
  49.                     @Override  
  50.                     public void onResponse(String response, int id) {  
  51.                         try {  
  52.                             JSONObject jsonObject = new JSONObject(response);  
  53.                             int status = jsonObject.getInt(Config.KEY_STATUS);  
  54.                             int errCode = jsonObject.getInt(Config.KEY_ERR_CODE);  
  55.                             if(status==1){  
  56.                                 successCallback.onSuccess(response,id);  
  57.                             }else if(status==0){  
  58.                                 failCallback.onFail(response);  
  59.                             }  
  60.                         } catch (JSONException e) {  
  61.                             e.printStackTrace();  
  62.                         }  
  63.   
  64.                     }  
  65.                 });  
  66.     }  
  67.     public interface ISuccessCallback{  
  68.         void onSuccess(String response,int id);  
  69.     };  
  70.     public interface IFailCallback{  
  71.         void onFail(String errCause);  
  72.     }  
  73. }  

接下來上登錄界面邏輯代碼:

LoginAty.java

[java]  view plain  copy
  1. package com.mero.wyt_register.activity;  
  2.   
  3. import android.app.ProgressDialog;  
  4. import android.content.Context;  
  5. import android.content.SharedPreferences;  
  6. import android.graphics.Bitmap;  
  7. import android.os.Handler;  
  8. import android.os.Message;  
  9. import android.text.TextUtils;  
  10. import android.util.Log;  
  11. import android.view.View;  
  12. import android.widget.EditText;  
  13. import android.widget.TextView;  
  14. import android.widget.Toast;  
  15.   
  16. import com.mero.wyt_register.Base.BaseSwipeBackLayout;  
  17. import com.mero.wyt_register.Config;  
  18. import com.mero.wyt_register.MyApplication;  
  19. import com.mero.wyt_register.R;  
  20. import com.mero.wyt_register.bean.User;  
  21. import com.mero.wyt_register.db.DbHelper;  
  22. import com.mero.wyt_register.net.LoginAction;  
  23. import com.mero.wyt_register.utils.Base64Utils;  
  24. import com.mero.wyt_register.widget.RoundButton;  
  25.   
  26. /** 
  27.  * Created by chenlei on 2016/11/16. 
  28.  */  
  29.   
  30. public class LoginAty extends BaseSwipeBackLayout implements View.OnClickListener{  
  31.     private static final String TAG = "LoginAty";  
  32.     private EditText edt_account = null;  
  33.     private EditText edt_pwd = null;  
  34.     private RoundButton btn_login_click_to_login;  
  35.     private TextView tx_register;  
  36.     private ProgressDialog pd;//進度條  
  37.     private static  final int DISMISS = 0 ;  
  38.     private User user ;  
  39.   
  40.   
  41.   
  42.   
  43.     @Override  
  44.     public void initData() {  
  45.     }  
  46.   
  47.     @Override  
  48.     public void initView() {  
  49.         edt_account = (EditText) findViewById(R.id.edt_login_account);  
  50.         edt_pwd = (EditText) findViewById(R.id.edt_login_pwd);  
  51.         tx_register = (TextView) findViewById(R.id.tx_login_click_to_register);  
  52.         btn_login_click_to_login = (RoundButton) findViewById(R.id.btn_login_click_to_login);  
  53.         btn_login_click_to_login.setOnClickListener(this);  
  54.         tx_register.setOnClickListener(this);  
  55.     }  
  56.     private final Handler handler = new Handler(){  
  57.         @Override  
  58.         public void handleMessage(Message msg) {  
  59.             if(msg.what==DISMISS){  
  60.                 pd.dismiss();  
  61.             }  
  62.         }  
  63.     };  
  64.     @Override  
  65.     public int getLayoutResourceId() {  
  66.         return R.layout.wyt_login;  
  67.     }  
  68.   
  69.     @Override  
  70.     public int getDialogIcon() {  
  71.         return 0;  
  72.     }  
  73.   
  74.     @Override  
  75.     public int setStatusBarColor() {  
  76.         return 0;  
  77.     }  
  78.   
  79.     @Override  
  80.     public void onClick(View v) {  
  81.         switch (v.getId()){  
  82.             case R.id.btn_login_click_to_login:  
  83.                 //點擊的是登錄按鈕  
  84.                 final String wyt_account = edt_account.getText().toString();//獲取賬號  
  85.                 final String wyt_pwd = edt_pwd.getText().toString();//獲取密碼  
  86.                 if(TextUtils.isEmpty(wyt_account)){  
  87.                     Toast.makeText(LoginAty.this,"賬號不能爲空",Toast.LENGTH_SHORT).show();  
  88.                     return;  
  89.                 }  
  90.                 if(TextUtils.isEmpty(wyt_pwd)){  
  91.                     Toast.makeText(LoginAty.this,"密碼不能爲空",Toast.LENGTH_SHORT).show();  
  92.                     return;  
  93.                 }  
  94.                 if(wyt_account.length()>20){  
  95.                     Toast.makeText(LoginAty.this,"您輸入的賬號過長",Toast.LENGTH_SHORT).show();  
  96.                     return;  
  97.                 }  
  98.                 if(wyt_pwd.length()>20){  
  99.                     Toast.makeText(LoginAty.this,"您輸入的密碼過長",Toast.LENGTH_SHORT).show();  
  100.                     return;  
  101.                 }  
  102.   
  103.                 String token =  Config.getTokenFromPreferences(this);  
  104.                 Log.e(TAG,"token的值"+token);  
  105.                 //顯示進度對話框  
  106.                 pd = ProgressDialog.show(this,"溫馨提示","正在登錄",false,true);  
  107.                 new LoginAction(Config.URL, Config.KEY_LOGIN, wyt_account, wyt_pwd, ""new LoginAction.ISuccessCallback() {  
  108.                     @Override  
  109.                     public void onSuccess(String s, String token) {  
  110.                         pd.setMessage("登錄成功");  
  111.                         //把token保存起來  
  112.                         SharedPreferences sharedPreferences = MyApplication.getMyApplication().getSharedPreferences(Config.ID, Context.MODE_PRIVATE);  
  113.                         SharedPreferences.Editor editor = sharedPreferences.edit();  
  114.                         editor.putString(Config.KEY_TOKEN,token);  
  115.                         editor.commit();  
  116.                         //獲取頭像  
  117.                         Bitmap bitmap = Base64Utils.stringtoBitmap(s);  
  118.                         user = new User();  
  119.                         user.setWyt_account(wyt_account);  
  120.                         user.setWyt_pwd(wyt_pwd);  
  121.                         user.setUser_icon(bitmap);  
  122.                         //保存該用戶到數據庫中  
  123.                         new DbHelper(LoginAty.this).insert(user,"user_wyt","person");  
  124.                         pd.dismiss();  
  125.                         showActivity(LoginAty.this,MainActivity.class);  
  126.                     }  
  127.                 }, new LoginAction.IFailCallback() {  
  128.                     @Override  
  129.                     public void onFail(String s) {  
  130.                         pd.setMessage("登錄失敗");  
  131.                         handler.sendEmptyMessageDelayed(DISMISS,1000);  
  132.                     }  
  133.                 });  
  134.   
  135. //                }  
  136.   
  137.                 break;  
  138.             case R.id.tx_login_click_to_register:  
  139.                 showActivity(LoginAty.this,RegisterAty.class);  
  140.                 break;  
  141.         }  
  142.   
  143.     }  
  144.   
  145.     @Override  
  146.     protected void onDestroy() {  
  147.         super.onDestroy();  
  148.     }  
  149. }  

下面是登錄網絡邏輯的封裝代碼:

LoginAction.java

[java]  view plain  copy
  1. package com.mero.wyt_register.net;  
  2.   
  3. import android.graphics.Bitmap;  
  4. import android.text.TextUtils;  
  5. import android.util.Log;  
  6.   
  7. import com.mero.wyt_register.Config;  
  8. import com.mero.wyt_register.utils.Base64Utils;  
  9. import com.zhy.http.okhttp.OkHttpUtils;  
  10. import com.zhy.http.okhttp.callback.StringCallback;  
  11.   
  12. import org.json.JSONException;  
  13. import org.json.JSONObject;  
  14.   
  15. import okhttp3.Call;  
  16.   
  17. /** 
  18.  * Creaed by chenlei on 2016/11/15. 
  19.  */  
  20.   
  21. public class LoginAction {  
  22.     private static  final  String TAG = "loginService";  
  23.     //登錄賬號密碼  
  24.     public LoginAction(String url, String action, String account, String pwd, String token, final ISuccessCallback successCallback, final IFailCallback failCallback){  
  25.         OkHttpUtils.post()  
  26.                 .url(url)  
  27.                 .addParams(Config.KEY_ACTION,action)  
  28.                 .addParams(Config.KEY_ACCOUNT,account)  
  29.                 .addParams(Config.KEY_PWD,pwd)  
  30.                 .addParams(Config.KEY_TOKEN,token)  
  31.                 .build().execute(new StringCallback() {  
  32.             @Override  
  33.             public void onError(Call call, Exception e, int id) {  
  34.                 if(failCallback!=null){  
  35.                     failCallback.onFail(e.getMessage());  
  36.                 }  
  37.             }  
  38.   
  39.             @Override  
  40.             public void onResponse(String response, int id) {  
  41.                 try {  
  42.                     JSONObject jsonObject =new JSONObject(response);  
  43.                     int status = jsonObject.getInt("status");  
  44.                     String iconStrBase64 = jsonObject.getString("user_icon");  
  45.                     String token = jsonObject.getString("token");  
  46.                     if(status==1){  
  47.                         if(null!=successCallback){  
  48.                             successCallback.onSuccess(iconStrBase64,token);  
  49.                         }  
  50.                     }else if(status==0){  
  51.                         if(null!=failCallback){  
  52.                             failCallback.onFail(response);  
  53.                         }  
  54.                     }  
  55.                 } catch (JSONException e) {  
  56.                     e.printStackTrace();  
  57.                 }  
  58.             }  
  59.         });  
  60.   
  61.     }  
  62.     public interface ISuccessCallback{  
  63.         void onSuccess(String s,String token);  
  64.     }  
  65.     public interface IFailCallback{  
  66.         void onFail(String s);  
  67.     }  
  68. }  


服務器端:

通過servlet實現對Action的處理,本實例僅採用了唯一的一個OnlyServlet。如果對servlet的使用不太會的話建議看下我的這篇關於servlet處理網頁客戶端的請求。本篇文章中不再累贅。首先我們來看看服務器的簡單結構。服務器端僅僅對註冊和登錄,頭像保存部分。

                                                                      
先上最關鍵的核心處理部分,本文中的登錄註冊等Action都在該servlet中處理。

OnlyServlet.java

[java]  view plain  copy
  1. package com.wyt_register;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.sql.ResultSet;  
  6. import java.sql.SQLException;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.annotation.WebServlet;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import org.json.JSONException;  
  15. import org.json.JSONStringer;  
  16.   
  17. import com.wyt_register.db.UserDao;  
  18. import com.wyt_register.md5Tool.Base64Utils;  
  19. import com.wyt_register.md5Tool.Md5Utils;  
  20.   
  21. /** 
  22.  * Servlet implementation class OnlyServlet 
  23.  */  
  24. @WebServlet("/OnlyServlet")  
  25. public class OnlyServlet extends HttpServlet {  
  26.     private static final long serialVersionUID = 1L;  
  27.          
  28.     /** 
  29.      * @see HttpServlet#HttpServlet() 
  30.      */  
  31.     public OnlyServlet() {  
  32.         super();  
  33.         // TODO Auto-generated constructor stub  
  34.     }  
  35.   
  36.     /** 
  37.      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
  38.      */  
  39.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  40.         // TODO Auto-generated method stub  
  41.         String action = null;//根據請求的行爲進行相應的操作  
  42.         if((action=request.getParameter(Config.KEY_ACTION))!=null){  
  43.             switch(action){  
  44. //          如果是註冊  
  45.             case Config.KEY_REGISTER:  
  46.                 System.out.println("正在請求註冊");  
  47. //              用戶註冊的賬號  
  48.                 String account_register = request.getParameter(Config.KEY_USER_ACCOUNT);  
  49.                 System.out.println(account_register);  
  50. //              用戶註冊的密碼  
  51.                 String pwd_register = request.getParameter(Config.KEY_USER_PWD);  
  52.                 System.out.println(pwd_register);  
  53. //              用戶上傳的頭像  
  54.                 String icon = request.getParameter(Config.KEY_USER_ICON);  
  55.                 if((null!=account_register)&&(null!=pwd_register)&&(null!=icon)){  
  56.                     //開啓註冊事務  
  57.                     //把唯一的賬號名的md5值作爲圖片的名字  
  58.                     StringBuilder sb0 = new StringBuilder("");  
  59.                     //保存到數據庫中的頭像圖片路徑  
  60.                     sb0.append("/image/").append(Md5Utils.encode(account_register)).append(".png");  
  61.                     String icon_addr = sb0.toString();  
  62.                     System.out.println("頭像圖片地址:"+icon_addr);  
  63.                     StringBuilder sb1 = new StringBuilder("");  
  64.                     //寫入到本地的頭像圖片路徑  
  65.                     sb1.append(Config.ADDR_ICON).append(Md5Utils.encode(account_register)).append(".png");  
  66.                     String local_icon_addr = sb1.toString();  
  67.                     System.out.println("保存到本地的地址"+local_icon_addr);  
  68.                     PrintWriter writer =response.getWriter();  
  69.                     //查詢用戶是否已經註冊過  
  70.                     try {  
  71.                         ResultSet set = UserDao.query(account_register);  
  72.                         //沒註冊過,需要註冊  
  73.                         if(!set.next()){  
  74.                             //保存上傳的頭像至本地  
  75.                             boolean isSuccessToSaveImageToLocal = Base64Utils.getPicFormatBASE64(icon,local_icon_addr );  
  76.                             if(isSuccessToSaveImageToLocal){  
  77.                                 //頭像上傳成功後然後再插入賬號密碼到數據庫  
  78.                                 boolean isSuccessToRegister = UserDao.insert(new Object[]{Config.KEY_ID,Config.KEY_USER_ACCOUNT,Config.KEY_USER_PWD,Config.KEY_USER_ICON_ADDR},new Object[]{null,account_register,pwd_register,icon_addr});  
  79.                                 if(isSuccessToRegister){  
  80.                                     //註冊成功  
  81.                                     writer.print("{\"status\":1,\"errCode\":0x00000000}");  
  82.                                 }else{  
  83.                                     //註冊失敗  
  84.                                     writer.print("{\"status\":0,\"errCode\":0x00000001}");  
  85.                                 }  
  86.                             }  
  87.                         }else{  
  88.                             //註冊過了  
  89.                             writer.print("{\"status\":0,\"errCode\":0x00000010}");  
  90.                         }  
  91.                     }                                  }  
  92.                             }  
  93.                         }else{  
  94.                             //註冊過了  
  95.                             writer.print("{\"status\":0,\"errCode\":0x00000010}");  
  96.                         }  
  97.                     } catch (SQLException e) {  
  98.                         // TODO Auto-generated catch block  
  99.                         e.printStackTrace();  
  100.                     }  
  101.                       
  102.                 }  
  103.                 break;  
  104. //          如果是登錄  
  105.             case
相關文章
相關標籤/搜索