Skip to content

Commit

Permalink
🔨 fix unexpected bugs on Android
Browse files Browse the repository at this point in the history
  • Loading branch information
Kangkang committed Feb 16, 2023
1 parent a7a79eb commit 9913709
Show file tree
Hide file tree
Showing 8 changed files with 141 additions and 65 deletions.
2 changes: 1 addition & 1 deletion android/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@

<!-- for override the enter animation-->
<activity android:name=".mask.DecoyMaskActivity"
android:theme="@style/TransparentTheme"
android:theme="@style/AppTheme.Normal"
/>
</application>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

Expand All @@ -28,6 +29,8 @@
import com.mobile.auth.gatewayauth.model.TokenRet;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
Expand Down Expand Up @@ -58,6 +61,8 @@ public class AuthClient {

private boolean sdkAvailable = true;

private boolean initSdkSuccess = false;

private int mLoginTimeout = 5;

// private MethodChannel mChannel;
Expand All @@ -81,10 +86,9 @@ public static AuthClient getInstance() {
}

public void initSdk(Object arguments, @NonNull MethodChannel.Result result, MethodChannel channel) {
if(!sdkAvailable){
if (!sdkAvailable) {
sdkAvailable = true;
}

try {
Gson gson = new Gson();
String jsonBean = gson.toJson(arguments);
Expand Down Expand Up @@ -114,13 +118,19 @@ public void onTokenSuccess(String s) {
try {
if (!TextUtils.isEmpty(s)) {
tokenRet = TokenRet.fromJson(s);
Log.d(TAG, "onTokenSuccess: " + tokenRet);
AuthResponseModel responseModel = AuthResponseModel.fromTokenRect(tokenRet);
//消息回调到flutter
channel.invokeMethod(DART_CALL_METHOD_ON_INIT, responseModel.toJson());
if (ResultCode.CODE_ERROR_ENV_CHECK_SUCCESS.equals(tokenRet.getCode())) {
if (ResultCode.CODE_SUCCESS.equals(tokenRet.getCode())) {
if (!initSdkSuccess) {
initSdkSuccess = true;
}
} else if (ResultCode.CODE_ERROR_ENV_CHECK_SUCCESS.equals(tokenRet.getCode())) {
//终端支持认证 当前环境可以进行一键登录 并且加速拉起授权页面
accelerateLoginPage(channel);
}

}
} catch (Exception e) {
e.printStackTrace();
Expand Down Expand Up @@ -154,13 +164,15 @@ public void onTokenFailed(String s) {
result.error(ResultCode.MSG_ERROR_UNKNOWN_FAIL, "当前无法获取Flutter Activity,请重启再试", null);
return;
}
Context context = activity.getBaseContext();
mAuthHelper = PhoneNumberAuthHelper.getInstance(context, tokenResultListener);
mAuthHelper.getReporter().setLoggerEnable(authModel.getEnableLog());
///开始初始化
mAuthHelper.setAuthSDKInfo(authModel.getAndroidSdk());
///检查环境
mAuthHelper.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN);
if (!initSdkSuccess) {
mAuthHelper = PhoneNumberAuthHelper.getInstance(activity, tokenResultListener);
mAuthHelper.getReporter().setLoggerEnable(authModel.getEnableLog());
///开始初始化
mAuthHelper.setAuthSDKInfo(authModel.getAndroidSdk());
} else {
///检查环境
mAuthHelper.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN);
}
result.success(true);
}

Expand All @@ -187,12 +199,19 @@ public void accelerateLoginPage(MethodChannel channel) {
@Override
public void onTokenSuccess(String s) {
try {
TokenRet tokenRet;
if (s != null && !s.equals("")) {
AuthResponseModel responseModel = AuthResponseModel.customModel(
MSG_GET_MASK_SUCCESS, preLoginSuccessMsg
);
// eventSink.success(responseModel.toJson());
channel.invokeMethod(DART_CALL_METHOD_ON_INIT, responseModel.toJson());

tokenRet = TokenRet.fromJson(s);
if (ResultCode.CODE_SUCCESS.equals(tokenRet.getCode())) {
AuthResponseModel responseModel = AuthResponseModel.customModel(
MSG_GET_MASK_SUCCESS, preLoginSuccessMsg
);
channel.invokeMethod(DART_CALL_METHOD_ON_INIT, responseModel.toJson());
} else {
AuthResponseModel responseModel = AuthResponseModel.fromTokenRect(tokenRet);
channel.invokeMethod(DART_CALL_METHOD_ON_INIT, responseModel.toJson());
}
}
} catch (Exception e) {
AuthResponseModel responseModel = AuthResponseModel.tokenDecodeFailed();
Expand Down Expand Up @@ -224,7 +243,7 @@ public void onTokenFailed(String s, String s1) {
/**
* 拉起登录授权页面并获取Token
*/
public void getLoginToken(Object arguments,@NonNull MethodChannel.Result result, @NonNull MethodChannel channel) {
public void getLoginToken(Object arguments, @NonNull MethodChannel.Result result, @NonNull MethodChannel channel) {
if (Objects.isNull(mAuthHelper) || !sdkAvailable) {
AuthResponseModel responseModel = AuthResponseModel.initFailed(initFailedMsg);
// eventSink.success(responseModel.toJson());
Expand All @@ -243,6 +262,13 @@ public void getLoginToken(Object arguments,@NonNull MethodChannel.Result result,
assert baseUIConfig != null;
clearCached();
baseUIConfig.configAuthPage(authModel.getAuthUIModel());

// override the decoy activity open enter animation
if (authModel.getAuthUIStyle().equals(Constant.DIALOG_PORT)) {
activity.overridePendingTransition(R.anim.zoom_in, 0);
} else {
activity.overridePendingTransition(R.anim.slide_up, 0);
}
tokenResultListener = new TokenResultListener() {
@Override
public void onTokenSuccess(String s) {
Expand All @@ -259,7 +285,14 @@ public void onTokenSuccess(String s) {
mAuthHelper.quitLoginPage();
mAuthHelper.setAuthListener(null);
clearCached();
} else if (ResultCode.CODE_ERROR_FUNCTION_TIME_OUT.equals(tokenRet.getCode())
|| ResultCode.MSG_ERROR_START_AUTHPAGE_FAIL.equals(tokenRet.getCode())) {
if (DecoyMaskActivity.isRunning) {
DecoyMaskActivity.isRunning = false;
activity.finish();
}
}
Log.d(TAG, "onTokenSuccess: " + tokenRet);
}
} catch (Exception e) {
AuthResponseModel responseModel = AuthResponseModel.tokenDecodeFailed();
Expand All @@ -286,12 +319,6 @@ public void onTokenFailed(String s) {
}
};
mAuthHelper.setAuthListener(tokenResultListener);
// override the decoy activity open enter animation
if (authModel.getAuthUIStyle().equals(Constant.DIALOG_PORT)) {
activity.overridePendingTransition(R.anim.zoom_in, 0);
} else {
activity.overridePendingTransition(R.anim.slide_up, 0);
}
Intent intent = new Intent(context, DecoyMaskActivity.class);
activity.startActivity(intent);
result.success(null);
Expand Down Expand Up @@ -352,6 +379,7 @@ public void onTokenSuccess(String s) {
mAuthHelper.setAuthListener(null);
clearCached();
}

Log.i(TAG, "tokenRet:" + tokenRet);
}
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,12 @@ public class DecoyMaskActivity extends Activity {

public static String TAG = DecoyMaskActivity.class.getSimpleName();

public static boolean isRunning = false;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
isRunning = true;

Log.i(TAG,"onCreate");

AuthClient authClient = AuthClient.getInstance();
Expand All @@ -39,6 +43,7 @@ protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);


//setContentView(R.layout.activity_calculator);
}

Expand All @@ -52,7 +57,6 @@ protected void onPause() {

@Override
protected void onResume() {
Log.i(TAG,"onResume");
if (isPause){
//TopActivityBack
Runnable runnable = new Runnable(){
Expand All @@ -72,4 +76,10 @@ public void run() {
public void finish() {
super.finish();
}

@Override
protected void onDestroy() {
super.onDestroy();
isRunning = false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ public static AuthResponseModel onCustomViewBlocTap(Integer viewId) {
return authResponseModel;
}

public static AuthResponseModel accelerateLoginPageSuccess() {
String now = Long.toString(System.currentTimeMillis());
AuthResponseModel authResponseModel = new AuthResponseModel();
authResponseModel.setResultCode(MSG_GET_MASK_SUCCESS);
authResponseModel.setMsg("加速拉起授权页面成功");
authResponseModel.setRequestId(now);
return authResponseModel;
}

public static AuthResponseModel fromTokenRect(TokenRet tokenRet) throws JSONException {

//TokenRet{vendorName='ct_sjl', code='600024', msg='终端支持认证', carrierFailedResultData=', requestId=8147329b-1618-4b9f-98ce-02e468d237ba', requestCode=0, token='null'}
Expand Down
7 changes: 4 additions & 3 deletions example/lib/pages/debug_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,13 @@ class _DebugPageState extends State<DebugPage> {
case AuthResultCode.noSIMCard:
SmartDialog.showToast("当前设备不支持一键登录(${resultCode.code})");
break;
case AuthResultCode.getMaskPhoneSuccess:
SmartDialog.showToast('预先取号成功');
break;

case AuthResultCode.envCheckSuccess:
SmartDialog.showToast('当前环境支持一键登录');
break;
case AuthResultCode.getMaskPhoneSuccess:
SmartDialog.showToast('预先取号成功');
break;
case AuthResultCode.unknownError:
case AuthResultCode.getTokenFailed:
case AuthResultCode.interfaceTimeout:
Expand Down
52 changes: 36 additions & 16 deletions example/lib/pages/release_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,31 @@ class _ReleasePageState extends State<ReleasePage> {
}

/// 登录成功处理
void _onEvent(dynamic event) async {
//print(event);
void _onEvent(AuthResponseModel responseModel) async {
final AuthResultCode resultCode = AuthResultCode.fromCode(
responseModel.resultCode!,
);
switch (resultCode) {
case AuthResultCode.success:
if (responseModel.token != null && responseModel.token!.isNotEmpty) {
//验证成功,获取到token
// await onToken(token: responseModel.token!);
}
break;
case AuthResultCode.envCheckSuccess:
SmartDialog.showToast('当前环境支持一键登录');
break;
case AuthResultCode.getMaskPhoneSuccess:
SmartDialog.showToast('预先取号成功');
//预先取号成功再调起授权页面
await AliAuthClient.login(timeout: 5);
break;
default:
// implement your logic
break;
}
}


@override
Widget build(BuildContext context) {
return Center(
Expand All @@ -75,19 +95,19 @@ class _ReleasePageState extends State<ReleasePage> {
//print(res);
},
),
ElevatedButton(
child: const Text('一键登陆'),
onPressed: () async {
try {
await AliAuthClient.login();
} on PlatformException catch (e) {
final AuthResultCode resultCode = AuthResultCode.fromCode(
e.code,
);
SmartDialog.showToast(resultCode.message);
}
},
),
// ElevatedButton(
// child: const Text('一键登陆'),
// onPressed: () async {
// try {
// await AliAuthClient.login();
// } on PlatformException catch (e) {
// final AuthResultCode resultCode = AuthResultCode.fromCode(
// e.code,
// );
// SmartDialog.showToast(resultCode.message);
// }
// },
// ),
],
),
);
Expand Down
50 changes: 29 additions & 21 deletions ios/Classes/SwiftFlutterAliAuthPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ public class SwiftFlutterAliAuthPlugin: NSObject, FlutterPlugin {
static var DART_CALL_METHOD_ON_INIT: String = "onEvent"

var sdkAvailable: Bool = true

var initSdkSuccess: Bool = false;

public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "flutter_ali_auth", binaryMessenger: registrar.messenger())
Expand Down Expand Up @@ -146,37 +148,43 @@ public class SwiftFlutterAliAuthPlugin: NSObject, FlutterPlugin {

// 设置参数
_authConfig = AuthConfig(params: params)
// 设置打印
TXCommonHandler.sharedInstance().getReporter().setConsolePrintLoggerEnable(_authConfig!.enableLog)

TXCommonHandler.sharedInstance().setAuthSDKInfo(sdk) { resultDict in
if(!initSdkSuccess){
// 设置打印
TXCommonHandler.sharedInstance().getReporter().setConsolePrintLoggerEnable(_authConfig!.enableLog)
TXCommonHandler.sharedInstance().setAuthSDKInfo(sdk) { resultDict in

var _responseMoedel: ResponseModel
var _responseMoedel: ResponseModel

guard let dict = resultDict as? [String: Any] else {
self.sdkAvailable = false
guard let dict = resultDict as? [String: Any] else {
self.sdkAvailable = false

_responseMoedel = ResponseModel(resultDict)
_responseMoedel = ResponseModel(resultDict)

self.methodChannel?.invokeMethod(SwiftFlutterAliAuthPlugin.DART_CALL_METHOD_ON_INIT, arguments: _responseMoedel.json)
self.methodChannel?.invokeMethod(SwiftFlutterAliAuthPlugin.DART_CALL_METHOD_ON_INIT, arguments: _responseMoedel.json)

return
}
_responseMoedel = ResponseModel(dict)
guard let code = dict["resultCode"] as? String else {
self.sdkAvailable = false
/// resultCode 未空 无法判断,直接返回
self.methodChannel?.invokeMethod(SwiftFlutterAliAuthPlugin.DART_CALL_METHOD_ON_INIT, arguments: _responseMoedel.json)
return
}
return
}
_responseMoedel = ResponseModel(dict)
guard let code = dict["resultCode"] as? String else {
self.sdkAvailable = false
/// resultCode 未空 无法判断,直接返回
self.methodChannel?.invokeMethod(SwiftFlutterAliAuthPlugin.DART_CALL_METHOD_ON_INIT, arguments: _responseMoedel.json)
return
}

self.methodChannel?.invokeMethod(SwiftFlutterAliAuthPlugin.DART_CALL_METHOD_ON_INIT, arguments: _responseMoedel.json)
self.methodChannel?.invokeMethod(SwiftFlutterAliAuthPlugin.DART_CALL_METHOD_ON_INIT, arguments: _responseMoedel.json)

if code == PNSCodeSuccess {
// 初始化成功:{msg: AppID、Appkey解析成功, resultCode: 600000, requestId: 481a2c9b50264cf3}
self.checkEnvAvailable()
if code == PNSCodeSuccess {
// 初始化成功:{msg: AppID、Appkey解析成功, resultCode: 600000, requestId: 481a2c9b50264cf3}
self.initSdkSuccess = true
self.checkEnvAvailable()
}
}
}else{
checkEnvAvailable();
}

}

// MARK: - 检查认证环境(checkEnvAvailableWithComplete)
Expand Down
2 changes: 1 addition & 1 deletion lib/src/internal/ali_auth_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class AliAuthClient {

/// 一键登陆 需要用try-catch[PlatformException]捕获插件返回的异常
/// 无返回内容,调用之后,会在[handleEvent][onEvent]返回回调
static Future<void> login({double timeout = 5.0}) {
static Future<void> login({int timeout = 5}) {
return _methodChannel.invokeMethod('login', timeout);
}

Expand Down

0 comments on commit 9913709

Please sign in to comment.