完善没有google play service情况下对google drive的操作

This commit is contained in:
CounterFire2023 2023-09-06 14:05:43 +08:00
parent 576a6296d5
commit f50a15b5ac
5 changed files with 157 additions and 101 deletions

View File

@ -14,7 +14,6 @@ import android.provider.MediaStore;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import android.view.Window; import android.view.Window;
import android.widget.Toast;
import androidx.annotation.MainThread; import androidx.annotation.MainThread;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
@ -32,7 +31,6 @@ import com.bytedance.sdk.open.tiktok.share.Share;
import com.cege.games.release.activity.CustomCaptureActivity; import com.cege.games.release.activity.CustomCaptureActivity;
import com.cege.games.release.activity.WebPageActivity; import com.cege.games.release.activity.WebPageActivity;
import com.cege.games.release.apple.AppleLoginActivity; import com.cege.games.release.apple.AppleLoginActivity;
import com.cege.games.release.dialog.QRCodeActivity;
import com.cege.games.release.wallet.WalletUtil; import com.cege.games.release.wallet.WalletUtil;
import com.facebook.AccessToken; import com.facebook.AccessToken;
import com.facebook.CallbackManager; import com.facebook.CallbackManager;
@ -47,12 +45,13 @@ import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.Scopes; import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.Scope; import com.google.android.gms.common.api.Scope;
import com.google.android.gms.tasks.Task; import com.google.android.gms.tasks.Task;
import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.DriveScopes;
import com.google.common.collect.Maps;
import com.google.firebase.analytics.FirebaseAnalytics; import com.google.firebase.analytics.FirebaseAnalytics;
import com.jc.jcfw.JcSDK; import com.jc.jcfw.JcSDK;
import com.jc.jcfw.appauth.AuthStateManager; import com.jc.jcfw.appauth.AuthStateManager;
@ -85,12 +84,10 @@ import org.cocos2dx.lib.Cocos2dxHelper;
import org.cocos2dx.lib.CocosJSHelper; import org.cocos2dx.lib.CocosJSHelper;
import org.json.JSONException; import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -105,8 +102,6 @@ public class MainActivity extends UnityPlayerActivity
private static final String TAG = MainActivity.class.getSimpleName(); private static final String TAG = MainActivity.class.getSimpleName();
public static MainActivity app; public static MainActivity app;
private Toast toast;
public static final String KEY_TITLE = "key_title"; public static final String KEY_TITLE = "key_title";
public static final String KEY_IS_CONTINUOUS = "key_continuous_scan"; public static final String KEY_IS_CONTINUOUS = "key_continuous_scan";
@ -128,8 +123,7 @@ public class MainActivity extends UnityPlayerActivity
public static final int FILE_SELECTOR_CODE = 0X014; public static final int FILE_SELECTOR_CODE = 0X014;
private String title; private String title;
private String funId; private String mFunID;
private QRCodeActivity qrCodeActivity;
// AppAuth // AppAuth
private AuthorizationService mAuthService; private AuthorizationService mAuthService;
@ -144,7 +138,7 @@ public class MainActivity extends UnityPlayerActivity
private TikTokOpenApi tiktokOpenApi; private TikTokOpenApi tiktokOpenApi;
public String getFunId() { public String getFunId() {
return funId; return mFunID;
} }
@NonNull @NonNull
@ -158,13 +152,10 @@ public class MainActivity extends UnityPlayerActivity
private AppEventsLogger fbLogger; private AppEventsLogger fbLogger;
private WalletUtil mWalletUtil; private WalletUtil mWalletUtil;
private Consumer<String> nextAction = null; private Consumer<String> loginCbAction = null;
public boolean isGooglePlayServicesAvailable() { public boolean isGooglePlayServicesAvailable() {
// return return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS;
// GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) ==
// ConnectionResult.SUCCESS;
return false;
} }
@Override @Override
@ -218,9 +209,9 @@ public class MainActivity extends UnityPlayerActivity
switch (requestCode) { switch (requestCode) {
case REQUEST_CODE_SCAN: case REQUEST_CODE_SCAN:
String result = CameraScan.parseScanResult(data); String result = CameraScan.parseScanResult(data);
Log.i(TAG, "scan qrcode with funId: " + funId + " result: " + result); Log.i(TAG, "scan qrcode with funId: " + mFunID + " result: " + result);
JcSDK.nativeCb(funId, null, result); JcSDK.nativeCb(mFunID, null, result);
funId = ""; mFunID = "";
break; break;
case REQUEST_CODE_PHOTO: case REQUEST_CODE_PHOTO:
parsePhoto(data); parsePhoto(data);
@ -237,15 +228,17 @@ public class MainActivity extends UnityPlayerActivity
exchangeAuthorizationCode(response); exchangeAuthorizationCode(response);
} else if (ex != null) { } else if (ex != null) {
Log.i(TAG, "Authorization flow failed: " + ex.getMessage()); Log.i(TAG, "Authorization flow failed: " + ex.getMessage());
JcSDK.nativeCb(mFunID, "Authorization flow failed: " + ex.getMessage(), null);
} else { } else {
Log.i(TAG, "No authorization state retained - reauthorization required"); Log.i(TAG, "No authorization state retained - reauthorization required");
JcSDK.nativeCb(mFunID, "No authorization state retained - reauthorization required", null);
} }
break; break;
case RC_SIGN_IN: case RC_SIGN_IN:
handleSignInResult(GoogleSignIn.getSignedInAccountFromIntent(data)); handleSignInResult(GoogleSignIn.getSignedInAccountFromIntent(data));
break; break;
case FILE_SELECTOR_CODE: case FILE_SELECTOR_CODE:
shareToTikTok(funId, data.getData()); shareToTikTok(mFunID, data.getData());
break; break;
case RC_REQUEST_DRIVE_TO_UPLOAD: case RC_REQUEST_DRIVE_TO_UPLOAD:
mExecutor.submit(() -> {mWalletUtil.uploadCfgWithGPS(_result -> {});}); mExecutor.submit(() -> {mWalletUtil.uploadCfgWithGPS(_result -> {});});
@ -265,7 +258,7 @@ public class MainActivity extends UnityPlayerActivity
} }
if (requestCode == REQUEST_CODE_SCAN && data != null) { if (requestCode == REQUEST_CODE_SCAN && data != null) {
if (data.getBooleanExtra("localImg", false)) { if (data.getBooleanExtra("localImg", false)) {
startPhotoCode(this.funId); startPhotoCode(this.mFunID);
next = true; next = true;
} }
} }
@ -275,9 +268,9 @@ public class MainActivity extends UnityPlayerActivity
handleSignInResult(task); handleSignInResult(task);
} }
if (requestCode == REQUEST_CODE_SCAN) { if (requestCode == REQUEST_CODE_SCAN) {
JcSDK.nativeCb(funId, "activity result with code: " + resultCode, null); JcSDK.nativeCb(mFunID, "activity result with code: " + resultCode, null);
} }
funId = ""; mFunID = "";
} }
} }
@ -336,9 +329,9 @@ public class MainActivity extends UnityPlayerActivity
@Override @Override
public void onPermissionsDenied(int requestCode, @NonNull List<String> list) { public void onPermissionsDenied(int requestCode, @NonNull List<String> list) {
// Some permissions have been denied // Some permissions have been denied
if ((requestCode == RC_CAMERA || requestCode == RC_READ_PHOTO) && null != funId && !"".equals(funId)) { if ((requestCode == RC_CAMERA || requestCode == RC_READ_PHOTO) && null != mFunID && !"".equals(mFunID)) {
JcSDK.nativeCb(funId, "User cancel", null); JcSDK.nativeCb(mFunID, "User cancel", null);
funId = ""; mFunID = "";
} }
} }
@ -385,8 +378,8 @@ public class MainActivity extends UnityPlayerActivity
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
JcSDK.nativeCb(funId, e.toString(), null); JcSDK.nativeCb(mFunID, e.toString(), null);
funId = ""; mFunID = "";
} }
} }
@ -394,18 +387,18 @@ public class MainActivity extends UnityPlayerActivity
asyncThread(() -> { asyncThread(() -> {
final String result = CodeUtils.parseQRCode(bitmap); final String result = CodeUtils.parseQRCode(bitmap);
if (null == result || "".equals(result)) { if (null == result || "".equals(result)) {
JcSDK.nativeCb(funId, "no qrdeata", null); JcSDK.nativeCb(mFunID, "no qrdeata", null);
} else { } else {
LogUtils.d("result:" + result); LogUtils.d("result:" + result);
JcSDK.nativeCb(funId, null, result); JcSDK.nativeCb(mFunID, null, result);
} }
funId = ""; mFunID = "";
}); });
} }
public void showQRScan(String funId, String title) { public void showQRScan(String funId, String title) {
this.title = title; this.title = title;
this.funId = funId; this.mFunID = funId;
checkCameraPermissions(); checkCameraPermissions();
} }
@ -421,7 +414,7 @@ public class MainActivity extends UnityPlayerActivity
// end of qrcode // end of qrcode
public void signWithGoogle(String funId) { public void signWithGoogle(String funId) {
this.funId = funId; this.mFunID = funId;
if (isGooglePlayServicesAvailable()) { if (isGooglePlayServicesAvailable()) {
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this); GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (account != null) { if (account != null) {
@ -441,7 +434,7 @@ public class MainActivity extends UnityPlayerActivity
performTokenRequest(state.createTokenRefreshRequest(), this::handleCodeExchangeResponse); performTokenRequest(state.createTokenRefreshRequest(), this::handleCodeExchangeResponse);
} else { } else {
Log.w(TAG, "already login, accessToken not expired, id token:: " + state.getIdToken()); Log.w(TAG, "already login, accessToken not expired, id token:: " + state.getIdToken());
JcSDK.nativeCb(this.funId, null, state.getIdToken()); JcSDK.nativeCb(this.mFunID, null, state.getIdToken());
} }
} else { } else {
Log.w(TAG, "not login"); Log.w(TAG, "not login");
@ -462,13 +455,14 @@ public class MainActivity extends UnityPlayerActivity
GoogleSignInAccount account = completedTask.getResult(ApiException.class); GoogleSignInAccount account = completedTask.getResult(ApiException.class);
Log.w(TAG, "signIn success: "); Log.w(TAG, "signIn success: ");
Log.w(TAG, "gsa idToken: " + account.getIdToken()); Log.w(TAG, "gsa idToken: " + account.getIdToken());
JcSDK.nativeCb(this.funId, null, account.getIdToken()); JcSDK.nativeCb(this.mFunID, null, account.getIdToken());
// Signed in successfully, show authenticated UI. // Signed in successfully, show authenticated UI.
} catch (ApiException e) { } catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason. // The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more // Please refer to the GoogleSignInStatusCodes class reference for more
// information. // information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode()); Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
JcSDK.nativeCb(this.mFunID, "signInResult:failed code=" + e.getStatusCode(), null);
} }
} }
@ -713,7 +707,14 @@ public class MainActivity extends UnityPlayerActivity
Log.d(TAG, "access token: " + state.getAccessToken()); Log.d(TAG, "access token: " + state.getAccessToken());
Log.d(TAG, "refresh token: " + state.getRefreshToken()); Log.d(TAG, "refresh token: " + state.getRefreshToken());
mAuthStateManager.replace(state); mAuthStateManager.replace(state);
JcSDK.nativeCb(this.funId, null, state.getIdToken()); if (loginCbAction != null) {
mExecutor.submit(() -> {
loginCbAction.accept("success");
loginCbAction = null;
});
} else {
JcSDK.nativeCb(this.mFunID, null, state.getIdToken());
}
} }
@WorkerThread @WorkerThread
@ -725,6 +726,7 @@ public class MainActivity extends UnityPlayerActivity
final String message = "Authorization Code exchange failed: " final String message = "Authorization Code exchange failed: "
+ ((authException != null) ? authException.error : ""); + ((authException != null) ? authException.error : "");
Log.d(TAG, message); Log.d(TAG, message);
JcSDK.nativeCb(mFunID, message, null);
} else { } else {
checkAuthStateAndCB(); checkAuthStateAndCB();
} }
@ -732,7 +734,7 @@ public class MainActivity extends UnityPlayerActivity
// sign with tiktok // sign with tiktok
public void signWithTiktok(String funId) { public void signWithTiktok(String funId) {
this.funId = funId; this.mFunID = funId;
Log.i(TAG, "login with tiktok: " + funId); Log.i(TAG, "login with tiktok: " + funId);
// STEP 1: Create an instance of TiktokOpenApi // STEP 1: Create an instance of TiktokOpenApi
@ -743,27 +745,6 @@ public class MainActivity extends UnityPlayerActivity
tiktokOpenApi.authorize(request); tiktokOpenApi.authorize(request);
} }
public void showQRCode(String funID, String str, String title, String oid) {
runOnUiThread(() -> {
if (qrCodeActivity == null) {
qrCodeActivity = new QRCodeActivity(getContext());
}
qrCodeActivity.showQRCode(str, title, oid);
qrCodeActivity.show();
});
}
public void showToast(String text) {
runOnUiThread(() -> {
if (toast == null) {
toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
} else {
toast.setDuration(Toast.LENGTH_SHORT);
toast.setText(text);
}
toast.show();
});
}
// begin of facebook login // begin of facebook login
private void initFacebookSDK() { private void initFacebookSDK() {
@ -776,27 +757,27 @@ public class MainActivity extends UnityPlayerActivity
AccessToken accessToken = AccessToken.getCurrentAccessToken(); AccessToken accessToken = AccessToken.getCurrentAccessToken();
Log.d(TAG, "Login Success:: accessToken: " + accessToken.getToken()); Log.d(TAG, "Login Success:: accessToken: " + accessToken.getToken());
if (!verifyFbAccessToken(accessToken)) { if (!verifyFbAccessToken(accessToken)) {
JcSDK.nativeCb(MainActivity.app.funId, "access token expired", null); JcSDK.nativeCb(MainActivity.app.mFunID, "access token expired", null);
} }
} }
@Override @Override
public void onCancel() { public void onCancel() {
Log.d(TAG, "Login cancel"); Log.d(TAG, "Login cancel");
JcSDK.nativeCb(MainActivity.app.funId, "user login cancel", null); JcSDK.nativeCb(MainActivity.app.mFunID, "user login cancel", null);
} }
@Override @Override
public void onError(FacebookException exception) { public void onError(FacebookException exception) {
Log.i(TAG, "Login error: " + exception.getMessage()); Log.i(TAG, "Login error: " + exception.getMessage());
JcSDK.nativeCb(MainActivity.app.funId, exception.getMessage(), null); JcSDK.nativeCb(MainActivity.app.mFunID, exception.getMessage(), null);
} }
}); });
} }
public void signWithFacebook(String funId) { public void signWithFacebook(String funId) {
Log.i(TAG, "login with facebook: " + funId); Log.i(TAG, "login with facebook: " + funId);
this.funId = funId; this.mFunID = funId;
AccessToken accessToken = AccessToken.getCurrentAccessToken(); AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (!verifyFbAccessToken(accessToken)) { if (!verifyFbAccessToken(accessToken)) {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email")); LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
@ -814,7 +795,7 @@ public class MainActivity extends UnityPlayerActivity
private boolean verifyFbAccessToken(AccessToken accessToken) { private boolean verifyFbAccessToken(AccessToken accessToken) {
boolean isLoggedIn = accessToken != null && !accessToken.isExpired(); boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
if (isLoggedIn) { if (isLoggedIn) {
JcSDK.nativeCb(this.funId, null, accessToken.getToken()); JcSDK.nativeCb(this.mFunID, null, accessToken.getToken());
return true; return true;
} else { } else {
return false; return false;
@ -824,7 +805,7 @@ public class MainActivity extends UnityPlayerActivity
public void signWithTwitter(String funId) { public void signWithTwitter(String funId) {
Log.i(TAG, "login with twitter: " + funId); Log.i(TAG, "login with twitter: " + funId);
this.funId = funId; this.mFunID = funId;
} }
public void logEvent(String content) { public void logEvent(String content) {
@ -841,7 +822,7 @@ public class MainActivity extends UnityPlayerActivity
} }
public void signWithApple(String funId) { public void signWithApple(String funId) {
this.funId = funId; this.mFunID = funId;
Log.i(TAG, "login with apple: " + funId); Log.i(TAG, "login with apple: " + funId);
runOnUiThread(() -> { runOnUiThread(() -> {
Intent intent = new Intent(this, AppleLoginActivity.class); Intent intent = new Intent(this, AppleLoginActivity.class);
@ -860,7 +841,7 @@ public class MainActivity extends UnityPlayerActivity
} }
public void shareToTikTok(String funId, Uri uriToImage) { public void shareToTikTok(String funId, Uri uriToImage) {
this.funId = funId; this.mFunID = funId;
grantUriPermission("com.zhiliaoapp.musically", grantUriPermission("com.zhiliaoapp.musically",
uriToImage, Intent.FLAG_GRANT_READ_URI_PERMISSION); uriToImage, Intent.FLAG_GRANT_READ_URI_PERMISSION);
grantUriPermission("com.ss.android.ugc.trill", grantUriPermission("com.ss.android.ugc.trill",
@ -915,6 +896,7 @@ public class MainActivity extends UnityPlayerActivity
public void storagePass(String funID, String account, String password) { public void storagePass(String funID, String account, String password) {
Log.i(TAG, String.format("storagePass with: %s | %s", funID, account)); Log.i(TAG, String.format("storagePass with: %s | %s", funID, account));
this.mFunID = funID;
mWalletUtil.updateParams(funID, account); mWalletUtil.updateParams(funID, account);
mWalletUtil.savePassToLocal(password, _file -> { mWalletUtil.savePassToLocal(password, _file -> {
if (isGooglePlayServicesAvailable()) { if (isGooglePlayServicesAvailable()) {
@ -928,7 +910,24 @@ public class MainActivity extends UnityPlayerActivity
} }
} else { } else {
AuthState state = mAuthStateManager.getCurrent(); AuthState state = mAuthStateManager.getCurrent();
mWalletUtil.uploadCfgWithApi(state.getAccessToken(), _result->{}); if (state.isAuthorized()) {
if (state.getNeedsTokenRefresh()) {
Log.d(TAG, "need refresh accessToken");
loginCbAction = _result -> {
mWalletUtil.uploadCfgWithApi(state.getAccessToken(), _r->{});
};
performTokenRequest(state.createTokenRefreshRequest(),
this::handleCodeExchangeResponse);
} else {
mWalletUtil.uploadCfgWithApi(state.getAccessToken(), _r->{});
}
} else {
Log.w(TAG, "not login");
loginCbAction = _result -> {
mWalletUtil.uploadCfgWithApi(state.getAccessToken(), _r->{});
};
mExecutor.submit(this::doAuth);
}
} }
}); });
// runOnUiThread(() -> { // runOnUiThread(() -> {
@ -943,6 +942,7 @@ public class MainActivity extends UnityPlayerActivity
public void authGetStoragePass(String funID, String account) { public void authGetStoragePass(String funID, String account) {
Log.i(TAG, "authGetStoragePass with: " + account); Log.i(TAG, "authGetStoragePass with: " + account);
this.mFunID = funID;
mWalletUtil.updateParams(funID, account); mWalletUtil.updateParams(funID, account);
if (isGooglePlayServicesAvailable()) { if (isGooglePlayServicesAvailable()) {
if (!mWalletUtil.localCfgExists(account)) { if (!mWalletUtil.localCfgExists(account)) {
@ -961,29 +961,34 @@ public class MainActivity extends UnityPlayerActivity
} else { } else {
if (!mWalletUtil.localCfgExists(account)) { if (!mWalletUtil.localCfgExists(account)) {
AuthState state = mAuthStateManager.getCurrent(); AuthState state = mAuthStateManager.getCurrent();
// 1. check whether the google account has been logged in, this situation occurs when non-google login
// 2. check if already had permission of drive appdata, add permission of drive appdata to auth_config
// 3. check if need refresh access token
if (state.isAuthorized()) {
if (state.getNeedsTokenRefresh()) {
Log.d(TAG, "need refresh accessToken");
loginCbAction = _result -> {
mWalletUtil.downloadCfgWithApi(state.getAccessToken(), _file -> { mWalletUtil.downloadCfgWithApi(state.getAccessToken(), _file -> {
mWalletUtil.getPassLocal(); mWalletUtil.getPassLocal();
}); });
// TODO:: };
// 1. check whether the google account has been logged in, this situation occurs performTokenRequest(state.createTokenRefreshRequest(),
// when non-google login this::handleCodeExchangeResponse);
// 2. check if already had permission of drive appdata, add permission of drive } else {
// appdata to auth_config Log.d(TAG, "access token no need refresh");
// 3. check if need refresh access token mWalletUtil.downloadCfgWithApi(state.getAccessToken(), _file -> {
// if (state.isAuthorized()) { mWalletUtil.getPassLocal();
// if (state.getNeedsTokenRefresh()) { });
// Log.d(TAG, "need refresh accessToken"); }
// performTokenRequest(state.createTokenRefreshRequest(), } else {
// this::handleCodeExchangeResponse); Log.w(TAG, "not login");
// } else { loginCbAction = _result -> {
// Log.d(TAG, "access token no need refresh"); mWalletUtil.downloadCfgWithApi(state.getAccessToken(), _file -> {
// WalletUtil.downloadCfgToLocal(funID, account); mWalletUtil.getPassLocal();
// WalletUtil.getPassLocal(this, funID, account); });
// } };
// } else { mExecutor.submit(this::doAuth);
// Log.w(TAG, "not login"); }
// mExecutor.submit(this::doAuth);
// }
} else { } else {
mWalletUtil.getPassLocal(); mWalletUtil.getPassLocal();
} }

View File

@ -14,6 +14,8 @@ import android.widget.TextView;
import com.cege.games.release.MainActivity; import com.cege.games.release.MainActivity;
import com.cege.games.release.R; import com.cege.games.release.R;
import com.jc.jcfw.util.FileUtils; import com.jc.jcfw.util.FileUtils;
import com.jc.jcfw.util.ThreadUtils;
import com.jc.jcfw.util.UIUtils;
import com.king.zxing.util.CodeUtils; import com.king.zxing.util.CodeUtils;
import java.util.List; import java.util.List;
@ -59,7 +61,7 @@ public class QRCodeActivity extends Dialog implements EasyPermissions.Permission
} }
new Thread(() -> { new Thread(() -> {
bitmap = CodeUtils.createQRCode(content, 500, null); bitmap = CodeUtils.createQRCode(content, 500, null);
MainActivity.app.runOnUiThread(() -> { ThreadUtils.runInMain(() -> {
titleLabel.setText(title); titleLabel.setText(title);
ivCode.setImageBitmap(bitmap); ivCode.setImageBitmap(bitmap);
}); });
@ -70,12 +72,12 @@ public class QRCodeActivity extends Dialog implements EasyPermissions.Permission
public void saveAndClose() { public void saveAndClose() {
new Thread(() -> { new Thread(() -> {
String uri = FileUtils.saveBitmap(baseContent, oid, bitmap); String uri = FileUtils.saveBitmap(baseContent, oid, bitmap);
MainActivity.app.runOnUiThread(() -> { ThreadUtils.runInMain(() -> {
if (uri != null && !"".equals(uri)) { if (uri != null && !"".equals(uri)) {
MainActivity.app.showToast("Wallet restore key had save to System Album"); UIUtils.showToast(baseContent, "Wallet restore key had save to System Album");
dismiss(); dismiss();
} else { } else {
MainActivity.app.showToast("Wallet restore key save fail"); UIUtils.showToast(baseContent, "Wallet restore key save fail");
} }
}); });
}).start(); }).start();
@ -96,7 +98,7 @@ public class QRCodeActivity extends Dialog implements EasyPermissions.Permission
@Override @Override
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) { public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
MainActivity.app.showToast("We need Write WRITE_EXTERNAL_STORAGE for backup Wallet Restore Key"); UIUtils.showToast(baseContent, "We need Write WRITE_EXTERNAL_STORAGE for backup Wallet Restore Key");
} }
@Override @Override

View File

@ -10,6 +10,7 @@ import com.cege.games.release.MainActivity;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import com.jc.jcfw.google.PayClient; import com.jc.jcfw.google.PayClient;
import com.jc.jcfw.util.ThreadUtils; import com.jc.jcfw.util.ThreadUtils;
import com.jc.jcfw.util.UIUtils;
import org.cocos2dx.lib.CocosJSHelper; import org.cocos2dx.lib.CocosJSHelper;
import org.json.JSONException; import org.json.JSONException;
@ -84,7 +85,7 @@ public class JcSDK {
} }
public static void showQRCode(String funid, String content) { public static void showQRCode(String funid, String content) {
MainActivity.app.showQRCode(funid, content, "", ""); UIUtils.showQRCode(MainActivity.app, content, "", "");
} }
public static void showWebPage(String funid, String url) { public static void showWebPage(String funid, String url) {
@ -193,13 +194,8 @@ public class JcSDK {
funId = MainActivity.app.getFunId(); funId = MainActivity.app.getFunId();
} }
Log.i(TAG, String.format("%s native cb, error: %s, data: %s", funId, error, dataStr )); Log.i(TAG, String.format("%s native cb, error: %s, data: %s", funId, error, dataStr ));
if (ThreadUtils.isMainThread()) {
JcSDK.runJS(funId, "jniCallback", result.toString());
} else {
String finalFunId = funId; String finalFunId = funId;
MainActivity.app.runOnUiThread(() -> JcSDK.runJS(finalFunId, "jniCallback", result.toString())); ThreadUtils.runInMain(() -> JcSDK.runJS(finalFunId, "jniCallback", result.toString()));
}
} }
public static void nativeCb(NativeResult result) { public static void nativeCb(NativeResult result) {

View File

@ -1,5 +1,6 @@
package com.jc.jcfw.util; package com.jc.jcfw.util;
import android.os.Handler;
import android.os.Looper; import android.os.Looper;
public class ThreadUtils { public class ThreadUtils {
@ -11,4 +12,13 @@ public class ThreadUtils {
public static boolean isMainThread() { public static boolean isMainThread() {
return Looper.getMainLooper() == Looper.myLooper(); return Looper.getMainLooper() == Looper.myLooper();
} }
public static void runInMain(Runnable action) {
if (ThreadUtils.isMainThread()) {
action.run();
} else {
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(action);
}
}
} }

View File

@ -0,0 +1,43 @@
package com.jc.jcfw.util;
import static androidx.core.content.ContextCompat.getSystemService;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.widget.Toast;
import androidx.annotation.MainThread;
import com.cege.games.release.MainActivity;
import com.cege.games.release.MainApplication;
import com.cege.games.release.dialog.QRCodeActivity;
import com.jc.jcfw.JcSDK;
public class UIUtils {
private static Toast toast;
@MainThread
public static void showToastReal(Context context,String text) {
if (toast == null) {
toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
} else {
toast.setDuration(Toast.LENGTH_SHORT);
toast.setText(text);
}
toast.show();
}
public static void showToast(Context context, String text) {
ThreadUtils.runInMain(() -> showToastReal(context, text));
}
@MainThread
public static void showQRCodeReal(Context context, String str, String title, String oid) {
QRCodeActivity qrCodeActivity = new QRCodeActivity(context);
qrCodeActivity.showQRCode(str, title, oid);
qrCodeActivity.show();
}
public static void showQRCode(Context context, String str, String title, String oid) {
ThreadUtils.runInMain(() -> showQRCodeReal(context, str, title, oid));
}
}