Implement Health Kit in Java in 10 minute - Huawei Developers

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

Related

Explore the world Trip Booking App- Part-1 login with Huawei ID

More information like this, you can visit HUAWEI Developer Forum​
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201346103655580149&fid=0101188387844930001
Introduction
This article is based on Huawei Mobile Services application. I have developed Trip Booking Android app. We can provide the solution for HMS based multiple kits such as Account Kit, Huawei Ads, Huawei Map, and Huawei Analysts to use in Trip Booking. So users can book any trip.
In this application, users can plan trips and advance books. It will provide the ongoing trip cities wise with weather forecasting so that users can easily plan a trip and book trip and also can find popular cities with budget hotels and much more.
Service Process
{
"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"
}
The process is described as follows:
1. A user signs in to your app using a HUAWEI ID.
2. Your app sends a sign-in request to the Account SDK.
3. The Account SDK brings up the user sign-in authorization interface, explicitly notifying the user of the content to be authorized based on the authorization scope contained in the sign-in request.
4. After the user authorizes your app to access the requested content, the Account SDK returns the authorization code to your app.
5. Based on the authorization code, your app obtains the access token, refresh token, and ID token from the HUAWEI Account Kit server.
6. Based on the access token, your app server obtains openId of the user from the HUAWEI Account Kit server.
7. If the access token or ID token has expired, your app server obtains a new access token or ID token using the refresh token.
Prerequisite
1. A computer (desktop or laptop).
2. A Huawei phone used for running the app with HMS Core (APK) 3.0.0.300 or later.
3. A data cable used for connecting the computer to the Huawei phone.
4. Android Studio 3.0 or later.
5. Java SDK 1.7 or later.
6. HMS Core SDK 4.0.0.300 or later.
7. Must have Huawei Developer Account.
Things Need To Be Done
1. Create an app in AppGallery Connect and enable the service.
2. Create an Android Studio project.
3. Start development with kit integration inside the application.
4. Launch the application.
Create a project on AppGalleryConnect portal
1. Navigate to AppGalleryConnect, create a new project.
2. Enter all details regarding your application, enable Account Kit API, after that download the configuration JSON file, and then add into your android studio project.
Create a project in Android Studio:
Navigate to android studio and create a new android project, provide all details of your project, and then add AGC and Account kit SDK dependencies.
1. Add maven URL and add following AppGalleryConnect classpath.
Code:
buildscript {
repositories {
maven {url 'http://developer.huawei.com/repo/'}
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.1'
classpath 'com.huawei.agconnect:agcp:1.0.0.300'
}
}
allprojects {
repositories {
maven {url 'http://developer.huawei.com/repo/'}
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
2. Add the following dependencies in app module based Gradle file, then sync your project.
Code:
implementation "com.google.code.gson:gson:2.8.5"
implementation('com.huawei.hms:hwid:4.0.4.300')
implementation "com.squareup.okhttp3:okhttp:3.14.2"
implementation 'com.squareup.okio:okio:1.14.1'
Start development with kit integration inside the application
I have created the following package inside the project.
LoginActivity
In this screen, I have integrated login functionality with Huawei Id.
Which cover the following APIs
1. Call the HuaweiIdAuthParamsHelper.setAuthorizationCode API to send an authorization request.
Code:
HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setAuthorizationCode().createParams();
2. Call the getService API of HuaweiIdAuthManager to initialize the HuaweiIdAuthService object.
Code:
HuaweiIdAuthService service = HuaweiIdAuthManager.getService(MainActivity.this, authParams);
3. Call the HuaweiIdAuthService.getSignInIntent method to bring up the HUAWEI ID sign-in authorization interface.
Code:
startActivityForResult(mAuthManager.getSignInIntent(), Constant.REQUEST_SIGN_IN_LOGIN);
4. Process the sign-in result after the authorization is complete.
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN) {
Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data);
if (authHuaweiIdTask.isSuccessful()) {
AuthHuaweiId huaweiAccount = authHuaweiIdTask.getResult();
Log.i(TAG, huaweiAccount.getDisplayName() + " signIn success ");
Log.i(TAG, "AccessToken: " + huaweiAccount.getAccessToken());
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("user", huaweiAccount.getDisplayName());
startActivity(intent);
this.finish();
} else {
Log.i(TAG, "signIn failed: " + ((ApiException) authHuaweiIdTask.getException()).getStatusCode());
}
}
if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN_CODE) {
//login success
Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data);
if (authHuaweiIdTask.isSuccessful()) {
AuthHuaweiId huaweiAccount = authHuaweiIdTask.getResult();
Log.i(TAG, "signIn get code success.");
Log.i(TAG, "ServerAuthCode: " + huaweiAccount.getAuthorizationCode());
} else {
Log.i(TAG, "signIn get code failed: " + ((ApiException) authHuaweiIdTask.getException()).getStatusCode());
}
}
}
MainActivity
In this screen, I have integrated all fragments which are related to application and also added Logout functionality.
Code:
public class MainActivity extends AppCompatActivity {
private static String TAG = MainActivity.class.getName();
private AppBarConfiguration mAppBarConfiguration;
private HuaweiIdAuthService mAuthManager;
private HuaweiIdAuthParams mAuthParam;
private void setUser(String name) {
NavigationView navigationView = findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
TextView navUsername = headerView.findViewById(R.id.txt_user_name);
navUsername.setText(name);
}
private void logOut() {
mAuthParam = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setIdToken()
.setAccessToken()
.createParams();
mAuthManager = HuaweiIdAuthManager.getService(this, mAuthParam);
Task<Void> signOutTask = mAuthManager.signOut();
signOutTask.addOnSuccessListener(aVoid -> {
Log.i(TAG, "signOut Success");
Intent intent = new Intent(this, LoginScreen.class);
startActivity(intent);
this.finish();
})
.addOnFailureListener(e -> Log.i(TAG, "signOut fail"));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
logOut();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Launch the application
Let us launch our application, see the result
If you have any doubts or queries. Leave your valuable comment in the comment section and do not forget to like and follow me.
References
https://developer.huawei.com/consumer/en/hms/huawei-accountkit
is it possible to sign in using phone number?
Very useful, thanks.

Huawei ML kit – Integration of Scene Detection

Introduction
To help understand the image content, the scene detection service can classify the scenario content of images and add labels, such as outdoor scenery, indoor places, and buildings.You can create more customised experiences for users based on the data detected from image. Currently Huawei supports detection of 102 scenarios. For details about the scenarios, refer to List of Scenario Identification Categories.
This service can be used to identify image sets by scenario and create intelligent album sets. You can also select various camera parameters based on the scene in your app, to help users to take better-looking photos.
Prerequisite
The scene detection service supports integration with Android 6.0 and later versions.
The scene detection needs READ_EXTERNAL_STORAGE and CAMERA in AndroidManifest.xml.
Implementation of dynamic permission for camera and storage is not covered in this article. Please make sure to integrate dynamic permission feature.
Development
  1. Register as a developer account in AppGallery Connect.
  2. Create an application and enable ML kit from AppGallery connect.
  3. Refer to Service Enabling. Integrate AppGallery connect SDK. Refer to AppGallery Connect Service Getting Started.
4. Add Huawei Scene detection dependencies in app-level build.gradle.
Code:
// ML Scene Detection SDK
implementation 'com.huawei.hms:ml-computer-vision-scenedetection:2.0.3.300'
// Import the scene detection model package.
implementation 'com.huawei.hms:ml-computer-vision-scenedetection-model:2.0.3.300'
implementation 'com.huawei.hms:ml-computer-vision-cloud:2.0.3.300'
 5. Sync the gradle.
We have an Activity (MainActivity.java) which has floating buttons to select static scene detection and live scene detection.
Static scene detection is used to detect scene in static images. When we select a photo, the scene detection service returns the results.
Camera stream (Live) scene detection can process camera streams, convert video frames into an MLFrame object, and detect scenarios using the static image detection method.
Implementation of Static scene detection
Code:
private void sceneDetectionEvaluation(Bitmap bitmap) {
//Create a scene detection analyzer instance based on the customized configuration.
MLSceneDetectionAnalyzerSetting setting = new MLSceneDetectionAnalyzerSetting.Factory()
// Set confidence for scene detection.
.setConfidence(confidence)
.create();
analyzer = MLSceneDetectionAnalyzerFactory.getInstance().getSceneDetectionAnalyzer(setting);
MLFrame frame = new MLFrame.Creator().setBitmap(bitmap).create();
Task<List<MLSceneDetection>> task = analyzer.asyncAnalyseFrame(frame);
task.addOnSuccessListener(new OnSuccessListener<List<MLSceneDetection>>() {
public void onSuccess(List<MLSceneDetection> result) {
// Processing logic for scene detection success.
for( MLSceneDetection sceneDetection : result) {
sb.append("Detected Scene : " + sceneDetection.getResult() + " , " + "Confidence : " + sceneDetection.getConfidence() + "\n");
tvResult.setText(sb.toString());
if (analyzer != null) {
analyzer.stop();
}
}
}})
.addOnFailureListener(new OnFailureListener() {
public void onFailure(Exception e) {
// Processing logic for scene detection failure.
// failure.
if (e instanceof MLException) {
MLException mlException = (MLException)e;
// Obtain the result code. You can process the result code and customize respective messages displayed to users.
int errorCode = mlException.getErrCode();
// Obtain the error information. You can quickly locate the fault based on the result code.
String errorMessage = mlException.getMessage();
Log.e(TAG, "MLException : " + errorMessage +", error code: "+ String.valueOf(errorCode));
} else {
// Other errors.
Log.e(TAG, "Exception : " + e.getMessage());
}
if (analyzer != null) {
analyzer.stop();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if(analyzer != null) {
analyzer.stop();
}
}
We can set the settings MLSceneDetectionAnalyzerSetting() and set the confidence level for scene detection. setConfidence() methods needs to get float value. After settings are fixed, we can create the analyzer with settings value. Then, we can set the frame with bitmap. Lastly, we have created a task for list of MLSceneDetection object. We have listener functions for success and failure. The service returns list of results. The results have two parameter which are result and confidence. We can set the response to textView tvResult.
{
"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"
}
More details, you can visit https://forums.developer.huawei.com/forumPortal/en/topic/0204400184662360088
we will get accuracy result ?

Read Daily Step Data with Health Kit

{
"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"
}
Hello everyone,
Especially recently when we realized how important the “health” issue is for us, we learned how important it is to act in order to lead a healthy life. For the days when we worked in the home office and forgot to act like as a human, we can follow our daily steps, how many steps we have taken in 3 months and how many calories we have burned. We develop sample app to use this properties. We used these features with the help of Health Kit.
Before step into development progress, let’s examine what is Huawei Health Kit and what are the main functions.
Huawei Health Kit :
HUAWEI Health Kit allows ecosystem apps to access fitness and health data of users based on their HUAWEI ID and authorization. For consumers, Health Kit provides a mechanism for fitness and health data storage and sharing based on flexible authorization. For developers and partners, Health Kit provides a data platform and fitness and health open capabilities, so that they can build related apps and services based on a multitude of data types. Health Kit connects the hardware devices and ecosystem apps to provide consumers with health care, workout guidance, and ultimate service experience.
Main Functions :
· 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 developers’ access to their health and fitness data, guaranteeing users’ data privacy and legal rights.
· Device access
Provides hardware devices (including fitness and health devices) with APIs for measuring and uploading data through the standard Bluetooth protocol.
You can browse this page to examine it in more detail.
https://developer.huawei.com/consumer/en/hms/huaweihealth/
Development Process
We learned about Huawei Health Kit and its main functions. Now, we can move on development part. Primarily, we should create a project on App Gallery Connect. You can follow the steps from the link below.
https://medium.com/huawei-developers/android-integrating-your-apps-with-huawei-hms-core-1f1e2a090e98
After all these steps, we need to apply for Health Kit.
Then, we need to select data and their permissions.
!!! To access health data we need to authenticate the user with Huawei ID.
Let’s continue by coding Data Controller to get our users’ step data.
Code:
private fun initDataController() {
val hiHealthOptions = HiHealthOptions.builder()
.addDataType(DataType.DT_CONTINUOUS_STEPS_DELTA, HiHealthOptions.ACCESS_READ)
.build()
val signInHuaweiId =
HuaweiIdAuthManager.getExtendedAuthResult(hiHealthOptions)
dataController = HuaweiHiHealth.getDataController(context!!, signInHuaweiId)
}
}
After creating the Data Controller, we write the read Daily function to get daily steps data of our users.
Code:
fun readDaily(startTime: Int, endTime: Int) {
val daliySummationTask =
dataController!!.readDailySummation(
DataType.DT_CONTINUOUS_STEPS_DELTA,
startTime,
endTime
)
daliySummationTask.addOnSuccessListener { sampleSet ->
sampleSet?.let { showSampleSet(it) }
}
daliySummationTask.addOnFailureListener { e ->
val errorCode: String? = e.message
val pattern: Pattern = Pattern.compile("[0-9]*")
val isNum: Matcher = pattern.matcher(errorCode)
when {
e is ApiException -> {
val eCode = e.statusCode
val errorMsg = HiHealthStatusCodes.getStatusCodeMessage(eCode)
}
isNum.matches() -> {
val errorMsg =
errorCode?.toInt()?.let { HiHealthStatusCodes.getStatusCodeMessage(it) }
}
else -> {
}
}
}
}
Let’s build the request body for reading activity records. We call the read method of the Data Controller to obtain activity records from the Health platform based on the conditions in the request body. Also, we should set time format. The daily hours reading format should be like this:
” yyyy-MM-dd hh: mm: ss “
Code:
fun getActivityRecord() {
val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault())
val startDate: Date = dateFormat.parse("yyyy-MM-dd hh:mm:ss")!!
val endDate: Date = dateFormat.parse("yyyy-MM-dd hh:mm:ss")!!
val readOptions = ReadOptions.Builder()
.read(DataType.DT_CONTINUOUS_STEPS_DELTA)
.setTimeRange(
startDate.time,
endDate.time,
TimeUnit.MILLISECONDS
)
.build()
val readReplyTask = dataController!!.read(readOptions)
readReplyTask.addOnSuccessListener { readReply ->
Log.i("TAG", "Success read an SampleSets from HMS core")
for (sampleSet in readReply.getSampleSets()) {
showSampleSet(sampleSet)
}
}.addOnFailureListener { e ->
val errorCode: String? = e.message
val pattern: Pattern = Pattern.compile("[0-9]*")
val isNum: Matcher = pattern.matcher(errorCode)
when {
e is ApiException -> {
val eCode = e.statusCode
val errorMsg = HiHealthStatusCodes.getStatusCodeMessage(eCode)
}
isNum.matches() -> {
val errorMsg =
errorCode?.toInt()?.let { HiHealthStatusCodes.getStatusCodeMessage(it) }
}
else -> {
}
}
}
}
Bonus : I used pagination to displaying step data for better user experience and resource management.
Code:
var count = 0
var today = Calendar.getInstance()
var nextDay = Calendar.getInstance()
nextDay.add(Calendar.DATE, -20)
var dateFormat = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
println("Today : " + dateFormat.format(Date(today.timeInMillis)))
stepViewModel.readToday()
stepViewModel.readDaily(dateFormat.format(Date(nextDay.timeInMillis)).toInt(), dateFormat.format(Date(today.timeInMillis)).toInt()-1)
binding.stepList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
if (!binding.stepList.canScrollVertically(1) && count<5) {
count++
var otherDay = Calendar.getInstance()
var nextDay = Calendar.getInstance()
otherDay.add(Calendar.DATE, -(20*count))
nextDay.add(Calendar.DATE, -((20*(count + 1)-1)))
stepViewModel.readDaily(dateFormat.format(Date(nextDay.timeInMillis)).toInt(), dateFormat.format(Date(otherDay.timeInMillis)).toInt())
}
}
})
Finally, we completed our development process. Let’s see how it looks in our project.
Conclusion
We have created an application where we can track our daily step count by taking advantage of the features provided by the Health Kit. I think it is necessary for all of us to face this reality. I hope it has been useful article for you. Your questions and opinions are very important to me.
References :
https://developer.huawei.com/consumer/en/hms/huaweihealth/

Expert: Doctor Consult using RxAndroid and MVVM with ML Kit (Product Visual Search API) in Android App.

Overview
In this article, I will create a Doctor Consult Demo App along with the integration of ML Product Visual Search Api. Which provides an easy interface to consult with doctor. Users can scan their prescriptions using Product Visual Search Api.
Previous Articles Link:
https://forums.developer.huawei.com/forumPortal/en/topic/0201829733289720014?fid=0101187876626530001
https://forums.developer.huawei.com/forumPortal/en/topic/0201817617825540005?fid=0101187876626530001
https://forums.developer.huawei.com/forumPortal/en/topic/0201811543541800017?fid=0101187876626530001
HMS Core Map Service Introduction
ML Kit allows your apps to easily leverage Huawei's long-term proven expertise in machine learning to support diverse artificial intelligence (AI) applications throughout a wide range of industries. Thanks to Huawei's technology accumulation, ML Kit provides diversified leading machine learning capabilities that are easy to use, helping you develop various AI apps.
Product Visual Search: This service searches for the same or similar products in the pre-established product image library based on a product photo taken by a user, and returns the IDs of those products and related information. In addition, to better manage products in real time, this service supports offline product import, online product adding, deletion, modification, and query, and product distribution.
Prerequisite
Huawei Phone EMUI 3.0 or later.
Non-Huawei phones Android 4.4 or later (API level 19 or higher).
Android Studio.
AppGallery Account.
App Gallery Integration process
Sign In and Create or Choose a project on AppGallery Connect portal.
Navigate to Project settings and download the configuration file.
Navigate to General Information, and then provide Data Storage location.
App Development
Create A New Project.
Configure Project Gradle.
Configure App Gradle.
Configure AndroidManifest.xml.
Create Activity class with XML UI.
Java:
package com.hms.doctorconsultdemo.ml;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.mlsdk.MLAnalyzerFactory;
import com.huawei.hms.mlsdk.common.MLException;
import com.huawei.hms.mlsdk.common.MLFrame;
import com.huawei.hms.mlsdk.productvisionsearch.MLProductVisionSearch;
import com.huawei.hms.mlsdk.productvisionsearch.MLVisionSearchProduct;
import com.huawei.hms.mlsdk.productvisionsearch.MLVisionSearchProductImage;
import com.huawei.hms.mlsdk.productvisionsearch.cloud.MLRemoteProductVisionSearchAnalyzer;
import com.huawei.hms.mlsdk.productvisionsearch.cloud.MLRemoteProductVisionSearchAnalyzerSetting;
import java.util.ArrayList;
import java.util.List;
public class ScanMainActivity extends BaseActivity {
private static final String TAG = ScanMainActivity.class.getName();
private static final int CAMERA_PERMISSION_CODE = 100;
MLRemoteProductVisionSearchAnalyzer analyzer;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
initializeProductVisionSearch();
}
private void init() {
if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED)) {
this.requestCameraPermission();
}
initializeProductVisionSearch();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 101);
}
private void requestCameraPermission() {
final String[] permissions = new String[]{Manifest.permission.CAMERA};
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(this, permissions, this.CAMERA_PERMISSION_CODE);
return;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101) {
if (resultCode == RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
if (bitmap != null) {
MLFrame mlFrame = new MLFrame.Creator().setBitmap(bitmap).create();
mlImageDetection(mlFrame);
}
}
}
}
private void mlImageDetection(MLFrame mlFrame) {
Task<List<MLProductVisionSearch>> task = analyzer.asyncAnalyseFrame(mlFrame);
task.addOnSuccessListener(products -> {
Log.d(TAG, "success");
displaySuccess(products);
})
.addOnFailureListener(e -> {
try {
MLException mlException = (MLException) e;
int errorCode = mlException.getErrCode();
String errorMessage = mlException.getMessage();
} catch (Exception error) {
// Handle the conversion error.
}
});
}
private void initializeProductVisionSearch() {
MLRemoteProductVisionSearchAnalyzerSetting settings = new MLRemoteProductVisionSearchAnalyzerSetting.Factory()
.setLargestNumOfReturns(16)
.setRegion(MLRemoteProductVisionSearchAnalyzerSetting.REGION_DR_CHINA)
.create();
analyzer
= MLAnalyzerFactory.getInstance().getRemoteProductVisionSearchAnalyzer(settings);
}
private void displaySuccess(List<MLProductVisionSearch> productVisionSearchList) {
List<MLVisionSearchProductImage> productImageList = new ArrayList<>();
String prodcutType = "";
for (MLProductVisionSearch productVisionSearch : productVisionSearchList) {
Log.d(TAG, "type: " + productVisionSearch.getType());
prodcutType = productVisionSearch.getType();
for (MLVisionSearchProduct product : productVisionSearch.getProductList()) {
productImageList.addAll(product.getImageList());
Log.d(TAG, "custom content: " + product.getCustomContent());
}
}
StringBuffer buffer = new StringBuffer();
for (MLVisionSearchProductImage productImage : productImageList) {
String str = "ProductID: " + productImage.getProductId() + "\nImageID: " + productImage.getImageId() + "\nPossibility: " + productImage.getPossibility();
buffer.append(str);
buffer.append("\n");
}
Log.d(TAG, "display success: " + buffer.toString());
ScanDataActivity.start(this, productImageList);
}
}
App Build 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"
}
Tips and Tricks
Images in PNG, JPG, JPEG, and BMP formats are supported. GIF images are not supported.
ML Kit complies with GDPR requirements for data processing.
Face detection requires Android phones with the Arm architecture.
Conclusion
In this article, we have learned how to integrate HMS ML Kit using Product Visual Search Api in Android application. After completely read this article user can easily implement HMS ML Kit using Product Visual Search Api. So that Users can scan their prescriptions using Product Visual Search Api.
Thanks for reading this article. Be sure to like and comment to this article, if you found it helpful. It means a lot to me.
References
HMS ML Docs:
https://developer.huawei.com/consum...-Guides/service-introduction-0000001050040017
HMS Training Videos -
https://developer.huawei.com/consumer/en/training/

Client Server Messaging App Using Socket in Android With Huawei Account Kit for Easy Login

{
"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

Categories

Resources