AliAuthDemoActivity.java 11.3 KB
Newer Older
1
package com.yidianling.user.ui;
konghaorui committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.mobile.auth.gatewayauth.AuthRegisterViewConfig;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.CustomInterface;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.PreLoginResultListener;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.model.InitResult;
29
import com.yidianling.user.R;
konghaorui committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

@Route(path = "/user/aliAuthDemo")
public class AliAuthDemoActivity extends Activity {
    private PhoneNumberAuthHelper mAlicomAuthHelper;
    private TokenResultListener mTokenListener;
    private Button mVaildBtn, mLoginBtn;
    private TextView mRetTV;
    private InitResult mAutCheckResult;
    private SparseArray<PermissionCallback> mPerMissionCallbackCache;
    private int mCurrentPermissionRequestCode = 0;
    private ProgressDialog mProgressDialog;
    private String token;
    private TextView mDynamicView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
47
        setContentView(R.layout.user_activity_ali_auth_demo);
konghaorui committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
        mVaildBtn = (Button) findViewById(R.id.vaild_button);
        mLoginBtn = (Button) findViewById(R.id.login_button);
        mRetTV = (TextView) findViewById(R.id.operator_name_tv);
        init();
    }

    private void initDynamicView() {
        mDynamicView = new TextView(getApplicationContext());
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        layoutParams.setMargins(0, dp2px(this, 450), 0, 0);
        mDynamicView.setText("-----  自定义view  -----");
        mDynamicView.setTextColor(0xff999999);
        mDynamicView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13.0F);
        mDynamicView.setLayoutParams(layoutParams);
    }

    public static int dp2px(Context context, float dipValue) {
        try {
            final float scale = context.getResources().getDisplayMetrics().density;
            return (int) (dipValue * scale + 0.5f);
        } catch (Exception e) {
            return (int) dipValue;
        }
    }

    private void init() {
        /*
         *   1.init get token callback Listener
         */
        mTokenListener = new TokenResultListener() {
            @Override
            public void onTokenSuccess(final String ret) {
                mDynamicView = null;
                AliAuthDemoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*
                         *   setText just show the result for get token。
                         *   use ret to verfiy number。
                         */
                        hideLoadingDialog();
                        token = ret;
                        mRetTV.setText("成功:\n" + ret);
                        mAlicomAuthHelper.quitAuthActivity();
                    }
                });
            }

            @Override
            public void onTokenFailed(final String ret) {
                mDynamicView = null;
                AliAuthDemoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*
                         *  setText just show the result for get token
                         *  do something when getToken failed, such as use sms verify code.
                         */
                        hideLoadingDialog();
                        mRetTV.setText("失败:\n" + ret);
                        mAlicomAuthHelper.quitAuthActivity();
                    }
                });
            }
        };

        /*
         *   2.init AlicomAuthHelper with tokenListener
         */
        mAlicomAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenListener);

        /*
         *   3.set debugMode when app is in debug mode, sdk will print log in debug mode
         */
//        if (isApkInDebug(this)) {
        mAlicomAuthHelper.setDebugMode(true);
//        }

        /*
         *   4.ask permission from user, this step is not necessary
         *   just do when your app is needed
         */
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            requestPermission(new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionCallback() {
                @Override
                public void onPermissionGranted(boolean isRequestUser) {
                    /*
                     *   5.sdk init
                     */
                    mAutCheckResult = mAlicomAuthHelper.checkAuthEnvEnable();
                }

                @Override
                public void onPermissionDenied(boolean isRequestUser) {
                    Toast.makeText(AliAuthDemoActivity.this, "请允许相关权限", Toast.LENGTH_LONG).show();
                }
            });
        } else {
            /*
             *   5.sdk init
             */
            mAutCheckResult = mAlicomAuthHelper.checkAuthEnvEnable();
        }

        mVaildBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoadingDialog("正在请求认证token");
                mAlicomAuthHelper.getAuthToken(5000);
            }
        });

        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initDynamicView();
                mAlicomAuthHelper.addAuthRegistViewConfig("my_tv", new AuthRegisterViewConfig.Builder()
                        .setView(mDynamicView)
                        .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                        .setCustomInterface(new CustomInterface() {
                            @Override
                            public void onClick(Context context) {
                                Toast.makeText(context, "点击自定义控件", Toast.LENGTH_LONG).show();
                            }
                        }).build());
                showLoadingDialog("正在请求登录Token");
                mAlicomAuthHelper.getLoginToken(5000);
            }
        });

        /*
         *   7.user sdk init result to do someting
         *   this step is also not necessary
         *   if you do this step, user experience maybe better
         */
        if (mAutCheckResult != null) {
            //judge the phone condition can use 4g auth
            if (!mAutCheckResult.isCan4GAuth()) {
                mVaildBtn.setClickable(false);
                mRetTV.setText("请开启移动网络后重试!");
            }
        }

        /*
         *   8.config authorization page ui to adapte app ui theme
         */
        mAlicomAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder()
                .setAppPrivacyOne("自定义协议", "https://www.aliyun.com/product/dypns")
                .setLogoImgPath("ic_launcher")
                .setPrivacyState(true)
                .setCheckboxHidden(true)
                .create());

        mAlicomAuthHelper.preLogin(5, new PreLoginResultListener() {
            @Override
            public void onTokenSuccess(final String s) {
                AliAuthDemoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        /*
                         *  推荐在登录页初始化的时候调用
                         *  如果没有合适的调用时机
                         *  不调用此接口也没关系
                         *  千万不要APP冷启动初始化就调用!!!!
                         *  最好判断用户是否登录,若已登录不要使用此接口!!!!
                         */
                        mRetTV.setText("预取号成功:" + s);
                    }
                });
            }

            @Override
            public void onTokenFailed(final String s, final String s1) {
                /*
                 *  预取号调用失败
                 *  不用太关注,还是可以直接在用户点击"登录"时,调用getLoginToken
                 */
                mRetTV.setText("预取号失败:" + s + s1);
            }
        });

    }

    @Override
    protected void onDestroy() {
        /*
         *   8.remember on destory
         */
        mAlicomAuthHelper.onDestroy();
        super.onDestroy();
    }

    /*
     *  Dynamic request application permissions
     */
    protected void requestPermission(String[] permissions, PermissionCallback callback) {
        int result = PackageManager.PERMISSION_GRANTED;
        for (String s : permissions) {
            if (ContextCompat.checkSelfPermission(this, s) != PackageManager.PERMISSION_GRANTED)
                result = PackageManager.PERMISSION_DENIED;
        }

        if (result == PackageManager.PERMISSION_GRANTED && callback != null) {
            callback.onPermissionGranted(false);
        } else {
            if (Build.VERSION.SDK_INT >= 23) {
                if (mPerMissionCallbackCache == null)
                    mPerMissionCallbackCache = new SparseArray<PermissionCallback>();
                mPerMissionCallbackCache.put(mCurrentPermissionRequestCode, callback);
                requestPermissions(permissions, mCurrentPermissionRequestCode++);
            } else if (callback != null) {
                callback.onPermissionDenied(false);
            }
        }
    }

    public interface PermissionCallback {
        void onPermissionGranted(boolean isRequestUser);

        void onPermissionDenied(boolean isRequestUser);
    }

    public boolean isApkInDebug(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }

    public void showLoadingDialog(String hint) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }
        mProgressDialog.setMessage(hint);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
    }

    public void hideLoadingDialog() {
        if (mProgressDialog != null)
            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
    }


}