More information like this, you can visit HUAWEI Developer Forum
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201320947104400266&fid=0101187876626530001
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Hi folks! In this guide I’ll explain how to integrate the Huawei Game Service with gdx-gamesvcs, a libGDX extension library for Game Services.
Medium Link: https://medium.com/huawei-developers/huawei-game-service-for-libgdx-games-3b189d8b4a82
What’s gdx-gamesvcs?
gdx-gamesvcs is a libGDX extension that aims to provide a cross-platforms API
for Game Services.
It supports the following services:
• Google Play Games;
• Apple Game Center;
• GameJolt;
• Amazon GameCircle;
• Kongregate;
• Huawei Game Service (starting from version 1.1.0-SNAPSHOT version)
For further information, please visit: https://github.com/MrStahlfelge/gdx-gamesvcs
Huawei Game Service for libGDX
It supports the following features:
- Account Kit: login, logout;
- Game Service: player info, achievements, leaderboards, game events;
- Drive Kit: save, load and delete data on Cloud
Requirements
• EMUI 3.0+ / Android 4.4+
• HMS Core 4.0.0.300+
• Android Studio 3.0+
Preparation
• Create an app in AppGallery Connect. The app type must be Game.
• Create a libGDX project.
• Generate a signature certificate.
• Generate a signature certificate fingerprint.
• Configure the signature certificate fingerprint.
• Add the app package name and save the configuration file.
• Configure the Maven repository address and AppGallery Connect gradle
plug-in.
• Configure the signature file in Android Studio.
For further information, please visit: https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#0
Finally coding!
Gradle:
implementation “de.golfgl.gdxgamesvcs:gdx-gamesvcs-android-huawei:1.1.0-SNAPSHOT”
Now, in your Activity extending the AndroidApplication class (a libGDX class), optionally implementing the IGameServiceListener (to listen events), You have to instantiate the HuaweiGameServicesClient, and then manage the lifecycle events. Like this:
Code:
public class GameServiceActivity extends AndroidApplication implements IGameServiceListener {
private IGameServiceClient gsClient = null;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//true if You want to manage data on Cloud
this.gsClient = HuaweiGameServicesClient(this, true);
this.gsClient.setListener(this);
initialize(gdxGameSvcsApp, config);
}
@Override
protected void onPause() {
super.onPause();
if (this.gsClient != null) {
this.gsClient.pauseSession();
}
}
@Override
protected void onResume() {
super.onResume();
if (this.gsClient != null) {
this.gsClient.resumeSession();
}
}
@Override
public void gsOnSessionActive() {
Log.d("SESSION", "ACTIVE");
}
@Override
public void gsOnSessionInactive() {
Log.d("SESSION", "INACTIVE");
}
@Override
public void gsShowErrorToUser(GsErrorType et, String msg, Throwable t) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
So? Unleash the power of the HuaweiGameServiceClient!
Code:
...
//ACCOUNT KIT
gsClient.logIn();
gsClient.logOff();
//GAME SERVICE
//achievements
gsClient.showAchievements();
gsClient.unlockAchievement("id");
gsClient.incrementAchievement("id", increment, completionPercentage);
gsClient.fetchAchievements(new IFetchAchievementsResponseListener() {
@Override
public void onFetchAchievementsResponse(Array<IAchievement> achievements) {
}
});
//leaderboards
gsClient.showLeaderboards("id");
gsClient.submitToLeaderboard("id", score, scoreTips);
gsClient.fetchLeaderboardEntries("id", limit, isRelatedToPlayer, new IFetchLeaderBoardEntriesResponseListener() {
@Override
public void onLeaderBoardResponse(Array<ILeaderBoardEntry> leaderBoard) {
}
});
//game events
gsClient.submitEvent("id", increment);
//DRIVE KIT
gsClient.saveGameState(null, gameState, progressValue, new ISaveGameStateResponseListener() {
@Override
public void onGameStateSaved(boolean success, String errorCode) {
}
});
gsClient.loadGameState(null, new ILoadGameStateResponseListener() {
@Override
public void gsGameStateLoaded(byte[] gameState) {
}
});
gsClient.deleteGameState(null, new ISaveGameStateResponseListener() {
@Override
public void onGameStateSaved(boolean success, String errorCode) {
}
});
...
Do You want moaAAaaRrRr?
Read my article about Huawei IAP for libGDX: Medium
https://medium.com/huawei-developers/huawei-iap-for-libgdx-games-eb5aec5662af
Nice and useful article
i am implementing game using huawei game service. I am from india, here drive kit is not working, is there alternative to save game progress
Related
More articles like this, you can visit HUAWEI Developer Forum
Want to retrieve health or fitness data of users based on their HUAWEI ID and show in your app?
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Health Kit provide main three feature:
Data storage
Provides a data platform for developers to store fitness and health data.
Data openness
Provides a wide range of fitness and health APIs and supports sharing of the various fitness and health data, including step count, weight, and heart rate.
Data access authorization management
Provides settings for users and developers so users can manage developer's access to their health and fitness data, guaranteeing users' data privacy and legal rights.
Developement
1.Register HUAWEI ID and apply for Account Service*
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/apply-id-0000001050069756
2. Applying for Health Kit in developer console*
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/apply-kitservice-0000001050071707
3. Integrate HMS Health Kit
In Build.gradle file,add the implementation.
Code:
implementation 'com.huawei.hms:hihealth-base:{5.0.0.300}
In AndroidManifest.xml file, add the app ID generated when the creating the app on HUAWEI Developers to the application section.
Code:
<meta-data
android:name="com.huawei.hms.client.appid"
android:value="APP ID"/>
4.Call the related APIs to display HUAWEI ID sign-in screen and authorization screen. The app can only access data upon user authorization.
Sign in via HMS Core SDK and apply for the scope to obtain the permissions to access the HUAWEI Health Kit APIs.
Code:
private void signInn() {
Log.i(TAG, "begin sign in");
List<Scope> scopeList = new ArrayList<>();
// Add scopes to apply for. The following only shows an example.
// Developers need to add scopes according to their specific needs.
// View and save steps in HUAWEI Health Kit.
scopeList.add(new Scope( Scopes.HEALTHKIT_STEP_BOTH));
// View and save height and weight in HUAWEI Health Kit.
scopeList.add(new Scope(Scopes.HEALTHKIT_CALORIES_BOTH));
// View and save the heart rate data in HUAWEI Health Kit.
scopeList.add(new Scope(Scopes.HEALTHKIT_DISTANCE_BOTH));
// Configure authorization parameters.
HuaweiIdAuthParamsHelper authParamsHelper =
new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM);
HuaweiIdAuthParams authParams =
authParamsHelper.setIdToken().setAccessToken().setScopeList(scopeList).createParams();
// Initialize the HuaweiIdAuthService object.
final HuaweiIdAuthService authService =
HuaweiIdAuthManager.getService(this.getContext(), authParams);
// Silent sign-in. If authorization has been granted by the current account,
// the authorization screen will not display. This is an asynchronous method.
Task<AuthHuaweiId> authHuaweiIdTask = authService.silentSignIn();
final Context context = this.getContext();
// Add the callback for the call result.
authHuaweiIdTask.addOnSuccessListener(new OnSuccessListener<AuthHuaweiId>() {
@Override
public void onSuccess(AuthHuaweiId huaweiId) {
// The silent sign-in is successful.
Log.i(TAG, "silentSignIn success");
try {
readData();
} catch (ParseException e) {
e.printStackTrace();
}
Toast.makeText(context, "silentSignIn success", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception exception) {
// The silent sign-in fails.
// This indicates that the authorization has not been granted by the current account.
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.i(TAG, "sign failed status:" + apiException.getStatusCode());
Log.i(TAG, "begin sign in by intent");
// Call the sign-in API using the getSignInIntent() method.
Intent signInIntent = authService.getSignInIntent();
MeFragment.this.startActivityForResult(signInIntent, REQUEST_SIGN_IN_LOGIN);
}
}
});
}
5.Build the condition for data query: a DataCollector object
Code:
DataCollector dataCollector = new DataCollector.Builder().setPackageName(context)
.setDataType(DataType.DT_CONTINUOUS_STEPS_DELTA)
.setDataStreamName("STEPS_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build();
6.Build time range and build condition-based query object.
Use the specified condition query object(call read Option) to call the data controller to query the sampling dataset.
Code:
public void readData() throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date startDate = dateFormat.parse("2020-03-17 09:00:00");
Date endDate = dateFormat.parse("2020-07-17 09:05:00");
ReadOptions readOptions = new ReadOptions.Builder()
.read(DataType.DT_CONTINUOUS_STEPS_DELTA)
.read(DataType.DT_CONTINUOUS_CALORIES_BURNT)
.read(DataType.DT_CONTINUOUS_DISTANCE_DELTA)
.setTimeRange(startDate.getTime(), endDate.getTime(), TimeUnit.MILLISECONDS)
.build();
Task<ReadReply> readReplyTask = dataController.read(readOptions);
readReplyTask.addOnSuccessListener(new OnSuccessListener<ReadReply>() {
@Override
public void onSuccess(ReadReply readReply) {
for (SampleSet sampleSet : readReply.getSampleSets()) {
showSampleSet(sampleSet);
Log.i(TAG,"*****************"+sampleSet);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
checkData.setText(e.toString()+"read");
}
});
}
7.the calories,distance and step are succesfully show in app.
Reference:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/overview-dev-android-0000001050071671
More articles like this, you can visit HUAWEI Developer Forum
HUAWEI Scene Kit
-Lightweight rendering engine that features high performance and low consumption.
-Provides advanced descriptive APIs for you to edit, operate, and render 3D materials.
-Adopts physically based rendering (PBR) pipelines to achieve realistic rendering effects.
-Easily load and display complicated 3D objects on Android phones.
-Can be apply on AR virtual fitting room, 3D virtual galleries for art, and VR remote teaching.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Supported Devices:
HMS Core 4.0.2.300 later
Android 8.0/EMUI 8.0 later
Suppport Vulkan graphics APIs.
Supported Formats:
1.Materials rendered:GITP,glb
2.gITF textures: png,jpeg
3.Sky box material: dds(cubeMap)
Implementation Process
1. Add build dependencies in the dependencies section.
Code:
implementation 'com.huawei.scenekit:sdk:1.5.0.300'
2.Create a SampleView that inherits from SceneView
(SceneView inherits from surfaceView and overrides methods including surfaceCreated,surfaceChanged, surfaceDestroyed, onTouchEvent, and onDraw)
Code:
public class SampleView extends SceneView {
public SampleView(Context context) {
super(context);
}
public SampleView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
}
3.Override the surfaceCreated method in SampleView and call the super method and load 3D scene materials, skybox materials, and lighting maps.
Code:
@Override
public void surfaceCreated(SurfaceHolder holder) {
super.surfaceCreated(holder);
// Loads the model of a scene by reading files from assets.
loadScene("scene.gltf");
// Loads skybox materials by reading files from assets.
loadSkyBox("skyboxTexture.dds");
// Loads specular maps by reading files from assets.
loadSpecularEnvTexture("specularEnvTexture.dds");
// Loads diffuse maps by reading files from assets.
loadDiffuseEnvTexture("diffuseEnvTexture.dds");
}
(dds,gltf will be stored in assets directory and assets is inside app directory)
4.You may override other surface lifecycle methods.
Code:
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
super.surfaceChanged(holder, format, width, height);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
super.surfaceDestroyed(holder);
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
return super.onTouchEvent(motionEvent);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
5.Create an Activity that inherits from Activity and call setContentView in the onCreate method to load the SampleView.
Code:
public class SampleActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
}
}
6.In acitivity_sample create the SampleView
Code:
<com.huawei.huaweitextocr.huawei.SampleView
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Reference Link:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/client-dev-0000001050162137-V5
Introduction
In this article, will explain how to develop peer to peer communication between Android phone and Lite wearable. To achieve it we have to use Wear Engine library. It will give us the solution for communication between Harmony wearable and android smartphone.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Requirements
1) DevEco IDE
2) Lite wearable watch
3) Android Smart phone
4) Huawei developer account
Integration process
The integration process contains two parts. Android smart phone side and Wear app side.
Android side
Step 1: Create the android project in Android Studio.
Step 2: Generate Android signature files.
Step 3: Generate SHA -256 from the keystore generated. Please refer this link: https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#0
Step 4: Navigate to Huawei developer console. Click on Huawei ID https://developer.huawei.com/consumer/en/console#/productlist/32.
Step 5: Create new product. Add the SHA-256 as first signed certificate.
Step 6: Click Wear Engine under App services.
Step 7: Click Apply for Wear Engine, agree to the agreement, and the screen for data permission application is displayed.
Wait for the approval.
Step 8: Open the project level build gradle of your Android project.
Step 9: Navigate to buildscript > repositories and add the Maven repository configurations.
Code:
maven {url 'https://developer.huawei.com/repo/'}
Step 10: Navigate to allprojects > repositories and add the Maven repository address.
Code:
maven {url 'https://developer.huawei.com/repo/'}
Step 11: Add wear engine sdk on the build gradle.
Code:
implementation 'com.huawei.hms:wearengine:{version}'
Step 12: Add the proguard rules in proguard-rules.pro
Code:
-keepattributes *Annotation*
-keepattributes Signature
-keepattributes InnerClasses
-keepattributes EnclosingMethod
-keep class com.huawei.wearengine.**{*;}
Step 13: Add code snippet to search for available device on the MainActivity.
Code:
private void searchAvailableDevices() {
DeviceClient deviceClient = HiWear.getDeviceClient(this);
deviceClient.hasAvailableDevices().addOnSuccessListener(new OnSuccessListener<Boolean>() {
@Override
public void onSuccess(Boolean result) {
checkPermissionGranted();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
}
});
}
Step 14: If the devices are available call for device permissions granted or not.
Code:
private void checkPermissionGranted() {
AuthClient authClient = HiWear.getAuthClient(this);
authClient.checkPermission(Permission.DEVICE_MANAGER).addOnSuccessListener(new OnSuccessListener<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
if (!aBoolean) {
askPermission();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
}
});
}
Step 15: If permission is not granted, ask for the permission.
Code:
private void askPermission() {
AuthClient authClient = HiWear.getAuthClient(this);
AuthCallback authCallback = new AuthCallback() {
@Override
public void onOk(Permission[] permissions) {
if (permissions.length != 0) {
checkCurrentConnectedDevice();
}
}
@Override
public void onCancel() {
}
};
authClient.requestPermission(authCallback, Permission.DEVICE_MANAGER)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void successVoid) {
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
}
});
}
Read full article
Tips & Tricks
Make sure you are generated the SHA - 256 fingerprint of proper keystore.
Follow the P2P generation steps properly.
Conclusion
In this article, we have learnt how to integrate Wear Engine library on Android application side and wearable side. Wear engine will allow us to communicate between Android application and Harmony Wear application without any barrier.
Reference
Harmony Official document - https://developer.harmonyos.com/en/docs/documentation/doc-guides/harmonyos-overview-0000000000011903
Wear Engine documentation - https://developer.huawei.com/consum...-Guides/service-introduction-0000001050978399
Certificate generation article - https://forums.developer.huawei.com/forumPortal/en/topic/0202465210302250053
P2P generation article - https://forums.developer.huawei.com/forumPortal/en/topic/0202466737940270075
Read full article
Thanks for you sharing~ And I also found other articles from https://forums.developer.huawei.com/forumPortal/en/home
What is the communication way for sending messages?
Image segmentation technology is gathering steam thanks to the development of multiple fields. Take the autonomous vehicle as an example, which has been developing rapidly since last year and become a showpiece for both well-established companies and start-ups. Most of them use computer vision, which includes image segmentation, as the technical basis for self-driving cars, and it is image segmentation that allows a car to understand the situation on the road and to tell the road from the people.
Image segmentation is not only applied to autonomous vehicles, but is also used in a number of different fields, including:
Medical imaging, where it helps doctors make diagnosis and perform tests
Satellite image analysis, where it helps analyze tons of data
Media apps, where it cuts people from video to prevent bullet comments from obstructing them.
It is a widespread application. I myself am also a fan of this technology. Recently, I've tried an image segmentation service from HMS Core ML Kit, which I found outstanding. This service has an original framework for semantic segmentation, which labels each and every pixel in an image, so the service can clearly, completely cut out something as delicate as a hair. The service also excels at processing images with different qualities and dimensions. It uses algorithms of structured learning to prevent white borders — which is a common headache of segmentation algorithms — so that the edges of the segmented image appear more natural.
I'm delighted to be able to share my experience of implementing this service here.
PreparationsFirst, configure the Maven repository and integrate the SDK of the service. I followed the instructions here to complete all these.
1. Configure the Maven repository address
Java:
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
...
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
2. Add build dependencies
Java:
dependencies {
// Import the base SDK.
implementation 'com.huawei.hms:ml-computer-vision-segmentation:2.1.0.301'
// Import the package of the human body segmentation model.
implementation 'com.huawei.hms:ml-computer-vision-image-segmentation-body-model:2.1.0.303'
}
3. Add the permission in the AndroidManifest.xml file.
Java:
// Permission to write to external storage.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Development Procedure1. Dynamically request the necessary permissions
Java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!allPermissionsGranted()) {
getRuntimePermissions();
}
}
private boolean allPermissionsGranted() {
for (String permission : getRequiredPermissions()) {
if (!isPermissionGranted(this, permission)) {
return false;
}
}
return true;
}
private void getRuntimePermissions() {
List<String> allNeededPermissions = new ArrayList<>();
for (String permission : getRequiredPermissions()) {
if (!isPermissionGranted(this, permission)) {
allNeededPermissions.add(permission);
}
}
if (!allNeededPermissions.isEmpty()) {
ActivityCompat.requestPermissions(
this, allNeededPermissions.toArray(new String[0]), PERMISSION_REQUESTS);
}
}
private static boolean isPermissionGranted(Context context, String permission) {
if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {
return true;
}
return false;
}
private String[] getRequiredPermissions() {
try {
PackageInfo info =
this.getPackageManager()
.getPackageInfo(this.getPackageName(), PackageManager.GET_PERMISSIONS);
String[] ps = info.requestedPermissions;
if (ps != null && ps.length > 0) {
return ps;
} else {
return new String[0];
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
return new String[0];
}
}
2. Create an image segmentation analyzer
Java:
MLImageSegmentationSetting setting = new MLImageSegmentationSetting.Factory()
// Set the segmentation mode to human body segmentation.
.setAnalyzerType(MLImageSegmentationSetting.BODY_SEG)
.create();
this.analyzer = MLAnalyzerFactory.getInstance().getImageSegmentationAnalyzer(setting);
3. Use android.graphics.Bitmap to create an MLFrame object for the analyzer to detect images
Java:
MLFrame mlFrame = new MLFrame.Creator().setBitmap(this.originBitmap).create();
4. Call asyncAnalyseFrame for image segmentation
Java:
// Create a task to process the result returned by the analyzer.
Task<MLImageSegmentation> task = this.analyzer.asyncAnalyseFrame(mlFrame);
// Asynchronously process the result returned by the analyzer.
task.addOnSuccessListener(new OnSuccessListener<MLImageSegmentation>() {
@Override
public void onSuccess(MLImageSegmentation mlImageSegmentationResults) {.
if (mlImageSegmentationResults != null) {
// Obtain the human body segment cut out from the image.
foreground = mlImageSegmentationResults.getForeground();
preview.setImageBitmap(MainActivity.this.foreground);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
return;
}
});
5. Change the image background
Java:
// Obtain an image from the album.
backgroundBitmap = Utils.loadFromPath(this, id, targetedSize.first, targetedSize.second);
BitmapDrawable drawable = new BitmapDrawable(backgroundBitmap);
preview.setBackground(drawable);
preview.setImageBitmap(this.foreground);
MLFrame mlFrame = new MLFrame.Creator().setBitmap(this.originBitmap).create();
Result
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
To learn more, please visit:
>> HUAWEI Developers official website
>> Development Guide
>> Reddit to join developer discussions
>> GitHub to download the sample code
>> Stack Overflow to solve integration problems
Follow our official account for the latest HMS Core-related news and updates.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, we will learn how to integrate Huawei Account kit in Android application. Account Kit provides you with simple, secure, and quick sign-in and authorization functions. Instead of entering accounts and passwords and waiting for authentication, users can just tap the button to quickly and securely sign in to your app with their HUAWEI IDs. It helps app user seamless login functionality to the app with large user base.
Supported Devices
Development Overview
You need to install Android Studio IDE and I assume that you have prior knowledge of Android application development.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
Android phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.8 or later.
Android Studio software installed.
HMS Core (APK) 4.X or later
Integration steps
Step 1. Huawei developer account and complete identity verification in Huawei developer website, refer to register Huawei ID.
Step 2. Create project in AppGallery Connect
Step 3. Adding HMS Core SDK
Let's start coding
How do I call sign in method?
[/B]
private void signInWithHuaweiID() {
AccountAuthParams authParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();
service = AccountAuthManager.getService(ClientActivity.this, authParams);
startActivityForResult(service.getSignInIntent(), 1212);
}
[B]
How do I get sign in result?
[/B][/B]
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// Process the authorization result to obtain the authorization code from AuthAccount.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1212) {
Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
if (authAccountTask.isSuccessful()) {
// The sign-in is successful, and the user's ID information and authorization code are obtained.
AuthAccount authAccount = authAccountTask.getResult();
Log.i("TAG", "serverAuthCode:" + authAccount.getAuthorizationCode());
userName = authAccount.getDisplayName();
makeConnect();
} else {
// The sign-in failed.
Log.e("TAG", "sign in failed:" + ((ApiException) authAccountTask.getException()).getStatusCode());
}
}
}
[B][B]
How do I start server?
[/B][/B][/B]
wManager = (WifiManager) getSystemService(WIFI_SERVICE);
serverIP = Formatter.formatIpAddress(wManager.getConnectionInfo().getIpAddress());
ip_txt.setText(serverIP);
class ServerThread implements Runnable {
@Override
public void run() {
try {
while (true) {
serverSocket = new ServerSocket(POST_NUMBER);
socket = serverSocket.accept();
output = new PrintWriter(socket.getOutputStream());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("TAG", " here ");
runOnUiThread(new Runnable() {
@Override
public void run() {
tv_status.setText("Waiting for conn at " + POST_NUMBER);
}
});
handler.post(new Runnable() {
@Override
public void run() {
tv_status.setText("Connected");
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
[B][B][B]
How do I send message using socket?
class SendMessage implements Runnable {
private String message;
SendMessage(String message) {
this.message = message;
}
@Override
public void run() {
output.write(message+"\r");
output.flush();
runOnUiThread(new Runnable() {
@Override
public void run() {
tv_chat.append("\n New Message: " + message);
ed_message.setText("");
}
});
Thread.interrupted();
}
}
How do I receive message using socket?
[/B]
private class ReadMessage implements Runnable {
@Override
public void run() {
while (true) {
try {
// Log.d("TAG","Server: Listening for message");
if(input!=null){
final String message = input.readLine();
if (message != null) {
handler.post(new Runnable() {
@Override
public void run() {
tv_chat.append("\n" + message );
}
});
}
}
} catch (IOException e) {
// Log.e("TAG","Error while receiving message");
e.printStackTrace();
}
}
}
}
[B]
Close the Socket and other connections
[/B][/B]
@Override
protected void onPause() {
super.onPause();
if (socket != null) {
try {
output.close();
input.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
[B][B]
How do I revoke auth permission?
[/B][/B][/B]
if(service!=null){
// service indicates the AccountAuthService instance generated using the getService method during the sign-in authorization.
service.cancelAuthorization().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
// Processing after a successful authorization cancellation.
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);
}
}
}
});
}
[B][B][B]
Result
Tricks and Tips
Makes sure that agconnect-services.json file added.
Make sure required dependencies are added
Make sure that service is enabled in AGC
Add required permissions
Conclusion
In this article, we have learnt how to integrate Huawei Account kit in Client Server messaging using Socket in Android application. You can check the desired result in the result section. Hoping Huawei Analytics kit capabilities are helpful to you as well, like this sample, you can make use of Huawei kits as per your requirement.
Thank you so much for reading. I hope this article helps you to understand the integration of Huawei Account kit in Android application.
Reference
Huawei Account Kit – Training video
Checkout in forum