[Huawei Developers] Freemind R:
More information like this, you can visit HUAWEI Developer Forum​

In this article, we will integrate various sign-in options in our single android application using Huawei Account kit and Google Sign-In.

Use case:

To allow user to sign in either by Huawei account or Google account by if device has HMS or GMS respectively.

Allow user to sign in using Huawei if device has HMS.

Allow user to sign in using Google if device has GMS.

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731095210.03223210897362484141024206611789:50510811074618:2800:4FAA40825A564243198A1D7C4CCF51E8FFD6DC8642C37CB9F1349D0DF53531EB.gif"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731095210.03223210897362484141024206611789:50510811074618:2800:4FAA40825A564243198A1D7C4CCF51E8FFD6DC8642C37CB9F1349D0DF53531EB.gif[/IMG]​

Huawei Account kit

Prerequisite

1) You must have Huawei developer account.

2) Huawei phone with HMS 4.0.0.300 or later

3) Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.

Setup:

1) Create a project in android studio.

2) Get the SHA-256 Key.

3) Create an app in the Huawei app gallery connect.

4) Enable account kit setting in Manage APIs section.

5) Provide the SHA-256 Key in App Information Section.

6) Provide storage location.

7) Enable Huwaei account under Auth Service in AGC

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731084528.64075165600900093551421196436844:50510811074618:2800:AB2DF7527B584E644501883B9EB345A399423C75ADFA5D6B83B19FD22449036B.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731084528.64075165600900093551421196436844:50510811074618:2800:AB2DF7527B584E644501883B9EB345A399423C75ADFA5D6B83B19FD22449036B.png[/IMG]​

8) After completing all the above points we need to download the agconnect-services.json from App Information Section. Place the json file in the app folder of the android project.

9) Enter the below maven url inside the repositories of buildscript and allprojects respectively ( project build.gradle file )

maven { url 'http://developer.huawei.com/repo/' }

10) Enter the below plugin in the app build.gradle file

apply plugin: 'com.huawei.agconnect'
dependencies {
implementation 'com.huawei.hms:hwid:4.0.0.300'
}

11) Now Sync the gradle.

Implementation

1) In this article, we will implement Authorization code method.

HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();
huaweiservice = HuaweiIdAuthManager.getService(MainActivity.this, authParams);
startActivityForResult(huaweiservice.getSignInIntent(), HUAWEI_SIGNIN);

2) To Process the sign-in result after the authorization is complete.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == HUAWEI_SIGNIN) {
com.huawei.hmf.tasks.Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data);
if (authHuaweiIdTask.isSuccessful()) {
//The sign-in is successful, and the user's HUAWEI ID information and authorization code are obtained.
AuthHuaweiId huaweiAccount = authHuaweiIdTask.getResult();
Log.i(TAG, "Authorization code:" + huaweiAccount.getAuthorizationCode());
Log.d(TAG, "name: " + huaweiAccount.getDisplayName());
Log.d(TAG, "email: " + huaweiAccount.getEmail());
Log.d(TAG , "avatar : "+huaweiAccount.getAvatarUriString());
launchLoggedinActivity(huaweiAccount.getFamilyName() , huaweiAccount.getGivenName() , huaweiAccount.getAvatarUriString(),"huawei");

} else {
// The sign-in failed.
Log.e(TAG, "sign in failed : " + ((com.huawei.hms.common.ApiException) authHuaweiIdTask.getException()).getStatusCode());
}
}
}

3) To handle silent Sign-in

The authorization is required only on first registration with the HUAWEI ID. Then no approval is required for subsequent registrations with the same HUAWEI ID.

private void handleHuaweiSilentSignIn() {
HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM).createParams();
HuaweiIdAuthService service = HuaweiIdAuthManager.getService(MainActivity.this, authParams);
com.huawei.hmf.tasks.Task<AuthHuaweiId> task = service.silentSignIn();
task.addOnSuccessListener(new OnSuccessListener<AuthHuaweiId>() {
@Override
public void onSuccess(AuthHuaweiId authHuaweiId) {
// Obtain the user's HUAWEI ID information.
Log.i(TAG, "displayName:" + authHuaweiId.getDisplayName());
launchLoggedinActivity(authHuaweiId.getFamilyName() , authHuaweiId.getGivenName() , authHuaweiId.getAvatarUriString(),"huawei");
}
});

task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// The sign-in failed. Try to sign in explicitly using getSignInIntent().
if (e instanceof ApiException) {
ApiException apiException = (ApiException)e;
Log.i(TAG, "sign failed status:" + apiException.getStatusCode());
}
}
});
}

4) To sign out from Huawei account

Task<Void> signOutTask = service.signOut();
signOutTask.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
Log.i(TAG, "signOut complete");
}
});

5) To revoke authorization

service.cancelAuthorization().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
// Processing after a successful authorization revoking.
Log.i(TAG, "onSuccess: ");
} else {
// Handle the exception.
Exception exception = task.getException();
if (exception instanceof ApiException){
int statusCode = ((ApiException) exception).getStatusCode();
Log.i(TAG, "onFailure: " + statusCode);
}
}
}

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731085624.08634188478438821695830596585207:50510811074618:2800:915A30AEBE2BF40414DCD08794C3184BD5B81F54FC397E1BFBFCD2687E3A62DC.jpg"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731085624.08634188478438821695830596585207:50510811074618:2800:915A30AEBE2BF40414DCD08794C3184BD5B81F54FC397E1BFBFCD2687E3A62DC.jpg[/IMG]

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731085833.93269412189823096559377151962419:50510811074618:2800:CA626C4CC1FFBBC29C1896D77D3AE3581D21EEAE69517A1A633EAB6B7AE734C9.jpg"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731085833.93269412189823096559377151962419:50510811074618:2800:CA626C4CC1FFBBC29C1896D77D3AE3581D21EEAE69517A1A633EAB6B7AE734C9.jpg[/IMG]

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731085940.33709770681341983462682054735944:50510811074618:2800:925630502EA0161ED026955142FAC145BCC8C5EB7CC4307E4D7DF62D4D3E8639.jpg"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731085940.33709770681341983462682054735944:50510811074618:2800:925630502EA0161ED026955142FAC145BCC8C5EB7CC4307E4D7DF62D4D3E8639.jpg[/IMG]​

Google Sign in

1) To add google play services, In your projects root-level build.gradle file, ensure that Googles Maven repository is included:

allprojects {
repositories {
google()

// If you're using a version of Gradle lower than 4.1, you must instead use:
// maven {
// url 'https://maven.google.com'
// }:
}
}

2) In app-level build.gradle file, declare Google Play services as a dependency:

dependencies {
implementation 'com.google.android.gms:play-services-auth:18.1.0'
}

3) To specify your app's SHA-1 fingerprint, go to Settings page of the Firebase console. Refer to Authenticating Your Client for details on how to get your app's SHA-1 fingerprint.

4) Enable Google Sign-In in the Firebase console:

In the Firebase console, open the Auth section.

On Sign in method tab, enable the Google sign-in method and click Save.

5) To Configure Google Sign-in and the GoogleSignInClient object.

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

6) To check for an existing sign-in user.

// Check for existing Google Sign In account, if the user is already signed in
// the GoogleSignInAccount will be non-null.
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);

If GoogleSignInAccount instanse is not null, user is already signed in.

7) On click of google sign in button, we will create a sign-in intent with the getSignInIntent method, and starting the intent with startActivityForResult.

private View.OnClickListener googleClickListner = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
};

8) To process the sign in result.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleGoogleSignInResult(task);
}
} private void handleGoogleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);

Log.d(TAG, "name: " + account.getDisplayName());
Log.d(TAG, "email: " + account.getEmail());
Log.d(TAG , "avatar : "+account.getPhotoUrl());
launchLoggedinActivity(account.getGivenName(), account.getFamilyName(),account.getPhotoUrl()!=null ? account.getPhotoUrl().toString():null, "google");

} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());

}
}

9) Code snippet for sign out from google is

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(LoggedInActivity.this, gso);
googleSignInClient.signOut();

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731091539.73514590291043350487739612257145:50510811074618:2800:3251891809EB701F2D3528BD01760BEDCBAF32F28737673C20D1368EB5166420.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731091539.73514590291043350487739612257145:50510811074618:2800:3251891809EB701F2D3528BD01760BEDCBAF32F28737673C20D1368EB5166420.png[/IMG]

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731091706.08746866391926019309970585233016:50510811084620:2800:BC1206EC09FD8C6F22F5F4C9CA025A4D92E1AFE3D907BCAE80ED971370F8DE46.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731091706.08746866391926019309970585233016:50510811084620:2800:BC1206EC09FD8C6F22F5F4C9CA025A4D92E1AFE3D907BCAE80ED971370F8DE46.png[/IMG]

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731092043.14576636568998538575358827750486:50510811084620:2800:A46C867591A335631155F1CFF174A1405370FDF64C37599BB2CFD1B1F1CC2514.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/940/588/2640091000001940588.20200731092043.14576636568998538575358827750486:50510811084620:2800:A46C867591A335631155F1CFF174A1405370FDF64C37599BB2CFD1B1F1CC2514.png[/IMG]

Huawei and Google Sign in Button Integration

Add the following code in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:visibility="gone"
android:id="@+id/login_layout"
android:orientation="vertical">
<com.google.android.gms.common.SignInButton
android:id="@+id/sign_in_button"
android:layout_width="242dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:visibility="gone"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content" />
<com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/hwi_sign_in"
android:layout_gravity="center_horizontal"
android:visibility="gone"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:background="#3b5998"
app:hwid_button_theme="hwid_button_theme_full_title"
app:hwid_corner_radius="hwid_corner_radius_small"
/>

</LinearLayout>
</RelativeLayout>

Permissions:

Add the following permissions in manifest.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

To check if device has HMS or GMS installed.

public class Utils {

public static boolean isSignedIn = false;

public static boolean isGooglePlayServicesAvailable(Activity activity) {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(activity);
if(status != ConnectionResult.SUCCESS) {
if(googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(activity, status, 2404).show();
}
return false;
}
return true;
}

public static boolean isHuaweiMobileServicesAvailable(Context context) {
if (HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context) == ConnectionResult.SUCCESS){
return true;
}
return false;
}

public static boolean isDeviceHuaweiManufacturer () {

String manufacturer = Build.MANUFACTURER;
Log.d("Device : " , manufacturer);
if (manufacturer.toLowerCase().contains("huawei")) {
return true;
}
return false;

}
}

Conclusion

We have developed a single application to allow sign in using either by Huawei or google.

Reference

https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050048870

https://developers.google.com/identity/sign-in/android/start-integrating​

​