베 이 징 동 쇼핑 몰 시리즈 14 --- 사용자 로그 인 및 app 로그 인 차단

이 항목 은 채소 둥지 에서 왔 습 니 다. 관심 있 는 사람 이 클릭 하 세 요.http://www.cniao5.com/course/
프로젝트 가 완료 되 었 습 니 다.https://github.com/15829238397/CN5E-shop
모방 경 동상 점 시리즈 0 - ---- 프로젝트 소개 모방 경 동상 점 시리즈 1 - --- fragmentTabHost 실현 밑부분 내 비게 이 션 표시 줄 모방 경 동상 점 시리즈 2 - ---- 사용자 정의 toolbar 모방 경 동상 점 시리즈 3 - ---- 포장 Okhttp 모방 경 동상 점 시리즈 4 - --- 윤 방 광고 표시 줄 모방 경 동상 점 시리즈 5 - --- 상품 추천 표시 줄 모방 경 동상 점 시리즈 6 - --- 하 라 리 셋 상 라 로 딩 상품 목록모방 경 동상 점 시리즈 7 - --- 상품 분류 페이지 모방 경 동상 점 시리즈 8 - --- 사용자 정의 수량 컨트롤 러 모방 경 동상 점 시리즈 9 - --- 카 트 데이터 메모리 모방 경 동상 점 시리즈 10 - --- 카 트 추가, 카 트 관리 기능 실현 모방 동상 점 시리즈 11 - --- 상품 정렬 기능 및 레이아웃 전환 실현 (Tablayot)베 이 징 동상 점 시리즈 12 - --- 상품 상세 정보 전시 (nativie 와 html 상호작용) 베 이 징 동상 점 시리즈 13 - --- 상품 공유 (sharesdk) 베 이 징 동상 점 시리즈 14 - --- 사용자 로그 인 및 app 로그 인 베 이 징 동상 성 시리즈 15 - --- 사용자 등록 차단,SMSSDK 통합 모방 경 동상 점 시리즈 16 - - 지불 SDK 통합 모방 경 동상 점 시리즈 17 - 지불 기능 실현 모방 경 동상 점 시리즈 18 - xml 파일 읽 기 (주소 선택 기) 모방 경 동상 점 시리즈 19 - 구 궁 격 주문 전시 모방 경 동상 점 시리즈 20 - - - 종장
머리말
이번 에는 초보 쇼핑 몰 로그 인 기능 과 앱 로그 인 차단 이 완 료 됩 니 다.로그 인 은 모두 가 알 고 있 을 것 입 니 다. 로그 인 차단 이 무엇 입 니까?로그 인 차단 이란 만약 에 이 app 에 로그 인하 지 않 았 다 면 제 주문 기능 을 직접 클릭 하면 app 은 자동 으로 로그 인 인터페이스 로 이동 하여 로그 인 을 완성 할 수 있 습 니 다. 로그 인 이 끝 난 후에 목표 페이지 (즉, 본 사례 의 주문 페이지) 로 바로 이동 합 니 다. 효과 도 는 다음 과 같 습 니 다.
사용자 로그 인. gif
내용.
인터페이스 분석
  • 제 인 터 페 이 스 는 사용자 정의 ToolBar 와 몇 개의 Text, 그리고 로그 인 종료 단추 가 있 습 니 다.구체 적 인 코드 는 다음 과 같다.
  • 
    
    
        
    
        
    
        
        
    
        
    
        
        
    
        
    
        
    • 用户登录界面就如所有的界面一样,不做赘述
    
    
    
        
    
        
    
        
        
    
        
        
    
        

    功能分析

    • 用户登录
      1.用户通过okhttp向服务器发出请求。
       String uri = Contents.API.LOGIN ;
            Map< String , String > params = new HashMap() ;
            params.put("phone" , phoneNum ) ;
            params.put("password" , DESUtil.encode(Contents.DES_KEY , pwd)) ;
    
            okhttpHelper.doPost(uri, new loadingSpotsDialog>(LoginActivity.this ) {
                @Override
                public void onErroe(Response response, int responseCode, Exception e) throws IOException {
                    this.closeSpotsDialog();
                }
    
                @Override
                public void callBackSucces(Response response, LoginRespMsg userLoginRespMsg) throws IOException {
                    this.closeSpotsDialog();
    
                    if(userLoginRespMsg.getStatus() == 1){
    
                        MyApplication.getInstance().putUser(userLoginRespMsg.getData() , userLoginRespMsg.getTocken());
                        closeKeyMode() ;
    
                        if (null == MyApplication.getInstance().getIntent()){
                            setResult(RESULT_OK);
                            finish();
                        }else {
                            MyApplication.jumpToTargetoActivity(LoginActivity.this);
                            finish();
                        }
    
                    }else {
                        showLoginErrorMsg() ;
                        phone.setText("");
                        password.setText("");
                    }
                }
            }, params);
    

    3. 새 도구 클래스, Shared Preferences 에서 사용자 정 보 를 액세스 합 니 다.
    package com.example.cne_shop.utils;
    
    import android.content.Context;
    import android.text.TextUtils;
    
    import com.example.cne_shop.bean.User;
    import com.example.cne_shop.contents.Contents;
    
    /**
     * Created by   on 2017/7/23.
     */
    
    public class UserLocalData {
    
        public static void putUser(Context context , User user){
    
            String user_json = JsonUtil.toJSON(user) ;
            PreferenceUtil.putString(context , Contents.USER_JSON , user_json);
        }
    
        public static void putToken(Context context , String token){
    
            PreferenceUtil.putString(context , Contents.TOKEN , token);
        }
    
        public static User getUser(Context context){
            String user_json = PreferenceUtil.getString(context , Contents.USER_JSON , null);
            if (!TextUtils.isEmpty(user_json)){
    
                return JsonUtil.fromJson(user_json , User.class) ;
            }
            return null ;
        }
    
        public static String getToken(Context context){
            String token = PreferenceUtil.getString(context , Contents.TOKEN , null);
            if (!TextUtils.isEmpty(token)){
    
                return JsonUtil.fromJson(token , String.class) ;
            }
            return null ;
        }
    
        public static void clearUser(Context context){
            PreferenceUtil.putString(context , Contents.USER_JSON , "");
        }
    
        public static void clearToken(Context context){
            PreferenceUtil.putString(context , Contents.TOKEN , "");
        }
    
    }
    
    

    2. 서버 가 로그 인 결 과 를 되 돌려 줍 니 다. 성공 하면 사용자 정 보 를 Shared Preferences 에 저장 하고 application 류 에 개인 변 수 를 만들어 Shared Preferences 에 저 장 된 사용자 정 보 를 application 의 개인 변수 에 복사 합 니 다.수시로 사용자 정 보 를 방문 하 는 데 편리 하 다.
    package com.example.cne_shop.application;
    
    import android.app.Activity;
    import android.app.Application;
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.widget.ImageView;
    
    import com.example.cne_shop.bean.User;
    import com.example.cne_shop.utils.UserLocalData;
    import com.facebook.drawee.backends.pipeline.Fresco;
    import com.squareup.picasso.Picasso;
    
    /**
     * Created by   on 2017/8/23.
     */
    
    public class MyApplication extends Application {
    
        public static final int START_FOR_RESULT  = 0 ;
        public static final int START_NO_RESULT  = 1 ;
    
        private User user ;
        private String token ;
        private static Intent intent ;
        private static  int startIntentStype ;
    
        public static int getStartIntentStype() {
            return startIntentStype;
        }
    
        public static void setStartIntentStype(int startIntentStype) {
            MyApplication.startIntentStype = startIntentStype;
        }
    
        public Intent getIntent() {
            return intent;
        }
    
        public void setIntent(Intent intent) {
            this.intent = intent;
        }
    
        public static MyApplication myApplication ;
    
        public static MyApplication getInstance(){
            return myApplication ;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            this.myApplication = this ;
            initUser();
            Fresco.initialize(this);
    //        NineGridView.setImageLoader(new PicassoImageLoader());
    
        }
    
        public void initUser(){
            this.user = UserLocalData.getUser(this );
            this.token = UserLocalData.getToken(this) ;
        }
    
        public User getUser(){
            return user ;
        }
    
        public String getToken(){
            return token ;
        }
    
        public void putUser(User user , String token){
    
            this.token = token ;
            this.user = user ;
            UserLocalData.putUser(this , user);
            UserLocalData.putToken(this , token);
        }
    
        public void clearUser(){
            this.user = null ;
            this.token = null ;
            UserLocalData.clearUser(this);
            UserLocalData.clearToken(this);
        }
    
        public static void jumpToTargetoActivity(Activity activity){
            activity.startActivity(intent);
            intent = null ;
        }
    
    }
    
    

    3. 앞으로 app 에 들 어 갈 때마다 application 에 user 값 이 있 는 지 자동 으로 감지 합 니 다.있 으 면 획득, 로그 인 한 사용자 인터페이스 를 직접 불 러 옵 니 다.
     @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            User user = MyApplication.getInstance().getUser() ;
            showUser(user) ;
        }
    
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        private void showUser(User user){
            if (user != null){
                cnToolbar.setUserPhotoIcon(this.getActivity() , user.getLogo_url() , R.drawable.default_head );
                cnToolbar.setUserNameText(user.getUsername());
                loginOut.setVisibility(View.VISIBLE);
                cnToolbar.setUserClickable(false);
    
            }else {
    
                cnToolbar.setUserNameText("    ");
                cnToolbar.setUserPhotoIcon(getContext() , R.drawable.default_head);
                loginOut.setVisibility(View.GONE);
                cnToolbar.setUserClickable(true);
            }
        }
    

    앱 로그 인 차단
    1. activity 전환 은 사용자 권한 이 필요 한 Activity 를 열 때 이 방법 을 사용 합 니 다.
     protected void startActivityWithLogin(Intent intent , boolean isNeedLogin , int startIntentStype){
    
            if (isNeedLogin){
    
                if(MyApplication.getInstance().getUser() == null){
    
                    Intent intent1 = new Intent(this , LoginActivity.class) ;
    
                    if (MyApplication.START_FOR_RESULT == startIntentStype){
                        startActivityForResult(intent1 , Contents.REQUEST_CODE);
                    }else if(MyApplication.START_NO_RESULT == startIntentStype){
                        MyApplication.getInstance().setIntent(intent);
                        startActivity(intent1);
                    }
    
                }else {
                    this.startActivity(intent);
                }
            }else {
                this.startActivity(intent);
            }
    }
    

    2. 네트워크 요청 의 경우.우리 가 제출 에 성공 할 때 status 변 수 를 얻 을 수 있 습 니 다. 이 변 수 는 현재 사용자 정보 가 사용 가능 한 지 여 부 를 설명 합 니 다.okhttp 요청 을 제출 할 때 status 인 자 를 추가 합 니 다.
    private String getUriWithParams( String uri ,Map formData){
    
            if (formData == null){
                formData = new HashMap<>(1);
            }
    
            String symbol = null ;
            int signNum = 0 ;
    
            String token = MyApplication.getInstance().getToken() ;
            if (!TextUtils.isEmpty(token)){
                formData.put("token" , MyApplication.getInstance().getToken());
            }
    
            for(String key : formData.keySet()){
                symbol = (signNum++ == 0 )? "?" : "&" ;
                uri = uri+symbol+key+"="+formData.get(key) ;
            }
    
            return uri ;
    
        }
    

    status 가 사용 가능 한 지 검증 합 니 다.
     else if (response.code() == TOKEN_ERROR ||response.code() == TOKEN_EXPRISE ||response.code() == TOKEN_MISSING  ){
                        callbackTokenError(callback , response) ;
                    }
    
  • 사용 할 수 없 으 면 로그 인 을 요구 합 니 다.
  •  public void onTokenError(Response response, int responseCode) {
    
            Toast.makeText(mContext , "TokenError" , Toast.LENGTH_SHORT).show();
    
            Intent intent = new Intent(mContext , LoginActivity.class);
            mContext.startActivity(intent);
    
            MyApplication.getInstance().clearUser();
        }
    

    Google 앱 로그 인 및 로그 인 차단 이 완료 되 었 습 니 다.자세 한 내용 은 페이지 의 원본 번 호 를 클릭 하 십시오.

    좋은 웹페이지 즐겨찾기