Android客户端Demo体验

本文为您介绍Android SDK Demo的运行步骤及示例代码,帮助您快速了解一键登录及本机号码校验功能。有关SDK的详细接入步骤及用法请参见一键登录 > Android客户端接入本机号码校验 > Android客户端接入

步骤一:下载SDK

登录号码认证产品控制台,在概览页面右侧API&SDK区域,单击立即下载,进入API&SDK页面,根据页面提示下载并解压对应SDK。

步骤二:打开Demo

使用Android Studio IDE,选择打开已有项目,选择到Demo文件夹项目载入过程会拉取相关依赖,请耐心等待。

重要

本文使用Android Studio 4.0版本进行演示。如果您使用的是其他的IDE版本,可能会存在构建报错,请按照提示修改对应Gradle版本。使用工具和环境搭建相关可参考准备工作

步骤三:设置认证方案

查看签名

使用Android Studio右侧面板,Gradle > 项目名称 > 签名文件所在module >Tasks > android > signingReport,查看签名

13

说明

包签名获取方式如下:

  • 方式一:上图的下方输出的MD5值移除冒号,将大写字母转换为小写字母即可生成包签名

  • 方式二:请通过手机终端下载并安装Android App签名获取工具,获取Android App的包签名信息。

查看包名

包名在app/build.gradle文件android.defaultConfig.applicationId属性。

06

创建认证方案

登录号码认证服务控制台,根据获取到的包名包签名创建认证方案

步骤四:替换密钥

找到module下的build.gradle文件,用上一步认证方案生成的密钥替换buildField.AUTH_SECRET字段。

步骤五:构建及运行

  1. Android系统的手机连接到电脑上并打开USB调试模式

  2. 点击IDE顶部工具菜单image..png,构建并运行项目。

  3. 功能试用。

    说明

    确保您的终端设备已开启SIM卡的移动数据网络(支持中国联通、中国移动的3G网络,但接口耗时会增加)。

    Screenshot_1684980161..png

    上图是Demo项目在手机上的运行效果。

代码示例

一键登录

package com.aliqin.mytel.login;

import static com.aliqin.mytel.Constant.THEME_KEY;
import static com.aliqin.mytel.uitls.MockRequest.getPhoneNumber;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.aliqin.mytel.BuildConfig;
import com.aliqin.mytel.MessageActivity;
import com.aliqin.mytel.R;
import com.aliqin.mytel.config.BaseUIConfig;
import com.aliqin.mytel.uitls.ExecutorManager;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.ResultCode;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.model.TokenRet;

/**
 * 进app直接登录的场景
 */
public class OneKeyLoginActivity extends Activity {

  private static final String TAG = OneKeyLoginActivity.class.getSimpleName();

  private EditText mTvResult;
  private PhoneNumberAuthHelper mPhoneNumberAuthHelper;
  private TokenResultListener mTokenResultListener;
  private ProgressDialog mProgressDialog;
  private int mUIType;
  private BaseUIConfig mUIConfig;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mUIType = getIntent().getIntExtra(THEME_KEY, -1);
    setContentView(R.layout.activity_login);
    mTvResult = findViewById(R.id.tv_result);
    sdkInit(BuildConfig.AUTH_SECRET);
    mUIConfig = BaseUIConfig.init(mUIType, this, mPhoneNumberAuthHelper);
    oneKeyLogin();
    mTvResult.setOnLongClickListener(
      new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
          mTvResult.setTextIsSelectable(true);
          mTvResult.setSelectAllOnFocus(true);
          ClipboardManager cm = (ClipboardManager) getSystemService(
            Context.CLIPBOARD_SERVICE
          );
          // 创建普通字符型ClipData
          ClipData mClipData = ClipData.newPlainText(
            "Label",
            mTvResult.getText()
          );
          // 将ClipData内容放到系统剪贴板里。
          cm.setPrimaryClip(mClipData);
          Toast
            .makeText(
              OneKeyLoginActivity.this,
              "登录token已复制",
              Toast.LENGTH_SHORT
            )
            .show();
          return false;
        }
      }
    );
  }

  public void sdkInit(String secretInfo) {
    mTokenResultListener =
      new TokenResultListener() {
        @Override
        public void onTokenSuccess(String s) {
          hideLoadingDialog();
          if (BuildConfig.NeedLogger) {
            Log.e(TAG, "获取token成功:" + s);
          }
          TokenRet tokenRet = null;
          try {
            tokenRet = TokenRet.fromJson(s);
            if (
              ResultCode.CODE_START_AUTHPAGE_SUCCESS.equals(tokenRet.getCode())
            ) {
              if (BuildConfig.NeedLogger) {
                Log.i(TAG, "唤起授权页成功:" + s);
              }
            }

            if (ResultCode.CODE_SUCCESS.equals(tokenRet.getCode())) {
              if (BuildConfig.NeedLogger) {
                Log.i(TAG, "获取token成功:" + s);
              }
              getResultWithToken(tokenRet.getToken());
              mPhoneNumberAuthHelper.setAuthListener(null);
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }

        @Override
        public void onTokenFailed(String s) {
          if (BuildConfig.NeedLogger) {
            Log.e(TAG, "获取token失败:" + s);
          }
          hideLoadingDialog();
          mPhoneNumberAuthHelper.hideLoginLoading();
          TokenRet tokenRet = null;
          try {
            tokenRet = TokenRet.fromJson(s);
            if (ResultCode.CODE_ERROR_USER_CANCEL.equals(tokenRet.getCode())) {
              //模拟的是必须登录 否则直接退出app的场景
              finish();
            } else {
              Toast
                .makeText(
                  getApplicationContext(),
                  "一键登录失败切换到其他登录方式",
                  Toast.LENGTH_SHORT
                )
                .show();
              Intent pIntent = new Intent(
                OneKeyLoginActivity.this,
                MessageActivity.class
              );
              startActivityForResult(pIntent, 1002);
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
          mPhoneNumberAuthHelper.quitLoginPage();
          mPhoneNumberAuthHelper.setAuthListener(null);
        }
      };
    mPhoneNumberAuthHelper =
      PhoneNumberAuthHelper.getInstance(this, mTokenResultListener);
    mPhoneNumberAuthHelper
      .getReporter()
      .setLoggerEnable(BuildConfig.NeedLogger);
    mPhoneNumberAuthHelper.setAuthSDKInfo(secretInfo);
  }

  /**
   * 进入app就需要登录的场景使用
   */
  private void oneKeyLogin() {
    mPhoneNumberAuthHelper.checkEnvAvailable();
    mUIConfig.configAuthPage();
    //用户控制返回键及左上角返回按钮效果
    mPhoneNumberAuthHelper.userControlAuthPageCancel();
    //用户禁用utdid
    //mPhoneNumberAuthHelper.prohibitUseUtdid();
    //授权页是否跟随系统深色模式
    mPhoneNumberAuthHelper.setAuthPageUseDayLight(true);
    //授权页物理返回键禁用
    //mPhoneNumberAuthHelper.closeAuthPageReturnBack(true);
    //横屏水滴屏全屏适配
    mPhoneNumberAuthHelper.keepAuthPageLandscapeFullSreen(true);
    //授权页扩大协议按钮选择范围至我已阅读并同意
    mPhoneNumberAuthHelper.expandAuthPageCheckedScope(true);
    getLoginToken(5000);
  }

  /**
   * 拉起授权页
   * @param timeout 超时时间
   */
  public void getLoginToken(int timeout) {
    mPhoneNumberAuthHelper.getLoginToken(this, timeout);
    showLoadingDialog("正在唤起授权页");
  }

  public void getResultWithToken(final String token) {
    ExecutorManager.run(
      new Runnable() {
        @Override
        public void run() {
          final String result = getPhoneNumber(token);
          OneKeyLoginActivity.this.runOnUiThread(
              new Runnable() {
                @Override
                public void run() {
                  mTvResult.setText("登录成功:" + result);
                  mTvResult.setMovementMethod(
                    ScrollingMovementMethod.getInstance()
                  );
                  mPhoneNumberAuthHelper.quitLoginPage();
                }
              }
            );
        }
      }
    );
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1002) {
      if (resultCode == 1) {
        mTvResult.setText("登录成功:" + data.getStringExtra("result"));
        mTvResult.setMovementMethod(ScrollingMovementMethod.getInstance());
      } else {
        //模拟的是必须登录 否则直接退出app的场景
        finish();
      }
    }
  }

  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) {
      mProgressDialog.dismiss();
    }
  }

  @Override
  protected void onResume() {
    super.onResume();
    mUIConfig.onResume();
  }
}

本机号码校验

package com.aliqin.mytel.auth;

import static com.aliqin.mytel.uitls.MockRequest.verifyNumber;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.Nullable;
import com.aliqin.mytel.BuildConfig;
import com.aliqin.mytel.R;
import com.aliqin.mytel.uitls.ExecutorManager;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.PreLoginResultListener;
import com.mobile.auth.gatewayauth.ResultCode;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.model.TokenRet;

public class NumberAuthActivity extends Activity {

  private static final String TAG = NumberAuthActivity.class.getSimpleName();
  private PhoneNumberAuthHelper mPhoneNumberAuthHelper;
  private TokenResultListener mVerifyListener;
  private Button mAuthButton;
  private EditText mNumberEt;
  private String phoneNumber;
  private ProgressDialog mProgressDialog;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_auth);
    mAuthButton = findViewById(R.id.auth_btn);
    mNumberEt = findViewById(R.id.et_number);
    mAuthButton.setOnClickListener(
      new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          phoneNumber = mNumberEt.getText().toString();
          //判断手机号是否合法
          if (!TextUtils.isEmpty(phoneNumber)) {
            showLoadingDialog("正在进行本机号码校验");
            numberAuth(5000);
          }
        }
      }
    );
    sdkInit();
    accelerateVerify(5000);
  }

  private void sdkInit() {
    mVerifyListener =
      new TokenResultListener() {
        @Override
        public void onTokenSuccess(String s) {
          if (BuildConfig.NeedLogger) {
            Log.i(TAG, "获取token成功:" + s);
          }
          try {
            TokenRet pTokenRet = TokenRet.fromJson(s);
            if (
              ResultCode.CODE_SUCCESS.equals(pTokenRet.getCode()) &&
              !TextUtils.isEmpty(pTokenRet.getToken())
            ) {
              getResultWithToken(pTokenRet.getToken(), phoneNumber);
            }
            mPhoneNumberAuthHelper.setAuthListener(null);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }

        @Override
        public void onTokenFailed(final String s) {
          if (BuildConfig.NeedLogger) {
            Log.i(TAG, "获取token失败:" + s);
          }
          NumberAuthActivity.this.runOnUiThread(
              new Runnable() {
                @Override
                public void run() {
                  hideLoadingDialog();
                  setResult(2);
                  finish();
                }
              }
            );
          mPhoneNumberAuthHelper.setAuthListener(null);
        }
      };
    mPhoneNumberAuthHelper =
      PhoneNumberAuthHelper.getInstance(
        getApplicationContext(),
        mVerifyListener
      );
    mPhoneNumberAuthHelper
      .getReporter()
      .setLoggerEnable(BuildConfig.NeedLogger);
  }

  /**
   * 加速校验
   * 进入输入手机号页面调用此接口,用户输入完手机号点击确定可以更快的获取token
   * @param timeout
   */
  public void accelerateVerify(int timeout) {
    mPhoneNumberAuthHelper.accelerateVerify(
      timeout,
      new PreLoginResultListener() {
        @Override
        public void onTokenSuccess(String vendor) {
          //成功时返回运营商简称
          if (BuildConfig.NeedLogger) {
            Log.i(TAG, "accelerateVerify:" + vendor);
          }
        }

        @Override
        public void onTokenFailed(String vendor, String errorMsg) {
          if (BuildConfig.NeedLogger) {
            Log.e(TAG, "accelerateVerify:" + vendor + ", " + errorMsg);
          }
        }
      }
    );
  }

  public void numberAuth(int timeout) {
    mPhoneNumberAuthHelper.setAuthListener(mVerifyListener);
    mPhoneNumberAuthHelper.getVerifyToken(timeout);
  }

  public void getResultWithToken(final String token, final String phoneNumber) {
    ExecutorManager.run(
      new Runnable() {
        @Override
        public void run() {
          final String result = verifyNumber(token, phoneNumber);
          NumberAuthActivity.this.runOnUiThread(
              new Runnable() {
                @Override
                public void run() {
                  hideLoadingDialog();
                  Intent pIntent = new Intent();
                  pIntent.putExtra("result", phoneNumber);
                  setResult(1, pIntent);
                  finish();
                }
              }
            );
        }
      }
    );
  }

  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) {
      mProgressDialog.dismiss();
    }
  }
}