DEV Community

Cover image for Integrating Huawei ML Kit(Text Translation) in Client Server Messaging App Using Socket in Android
HMS Community
HMS Community

Posted on

Integrating Huawei ML Kit(Text Translation) in Client Server Messaging App Using Socket in Android

Introduction

In this article, we will learn how to integrate Huawei ML kit in Android application. ML Kit provides many text service, you can check these services in the link provided in the reference section , in this sample we will be integrating one of its text service I.e. On-device translation, it translates text from the source language into the target language with the support of an on-device model, even when no Internet service is available.

Supported Devices

Image description
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?

private void signInWithHuaweiID() {

AccountAuthParams authParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();

service = AccountAuthManager.getService(ClientActivity.this, authParams);

startActivityForResult(service.getSignInIntent(), 1212);

}
Enter fullscreen mode Exit fullscreen mode

How do I get sign in result?

@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());

}

}

}
Enter fullscreen mode Exit fullscreen mode

How do I start server?

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();

}

}

}
Enter fullscreen mode Exit fullscreen mode

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();

}

}
Enter fullscreen mode Exit fullscreen mode

How do I receive message using socket?

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();

}

}

}

}
Enter fullscreen mode Exit fullscreen mode

Close the Socket and other connections

@Override

protected void onPause() {

super.onPause();

if (socket != null) {

try {

output.close();

input.close();

socket.close();



} catch (IOException e) {

e.printStackTrace();

}

}

}
Enter fullscreen mode Exit fullscreen mode

How do I revoke auth permission?

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);

}

}

}

});

}
Enter fullscreen mode Exit fullscreen mode

How do I translate message using ML Text Service?

private void translateMessage(String text) {

MLApplication.getInstance().setApiKey(API_KEY);

// create an offline translator.

MLLocalTranslateSetting setting = new MLLocalTranslateSetting.Factory()

// Set the source language code. The ISO 639-1 standard is used. This parameter is mandatory. If this parameter is not set, an error may occur.

.setSourceLangCode("en")

// Set the target language code. The ISO 639-1 standard is used. This parameter is mandatory. If this parameter is not set, an error may occur.

.setTargetLangCode("hi")

.create();

myLocalTranslator = MLTranslatorFactory.getInstance().getLocalTranslator(setting);

// Set the model download policy.

MLModelDownloadStrategy downloadStrategy = new MLModelDownloadStrategy.Factory()

.needWifi()// It is recommended that you download the package in a Wi-Fi environment.

.create();

// Create a download progress listener.

MLModelDownloadListener modelDownloadListener = new MLModelDownloadListener() {

@Override

public void onProcess(long alreadyDownLength, long totalLength) {

runOnUiThread(new Runnable() {

@Override

public void run() {

// Display the download progress or perform other operations.

}

});

}

};

myLocalTranslator.preparedModel(downloadStrategy, modelDownloadListener).

addOnSuccessListener(new OnSuccessListener<Void>() {

@Override

public void onSuccess(Void aVoid) {

// Called when the model package is successfully downloaded.

// input is a string of less than 5000 characters.

final Task<String> task = myLocalTranslator.asyncTranslate(text);

// Before translation, ensure that the models have been successfully downloaded.

task.addOnSuccessListener(new OnSuccessListener<String>() {

@Override

public void onSuccess(String translated) {

// Processing logic for detection success.

Log.d("TAG", "Text : " + translated);

}

}).addOnFailureListener(new OnFailureListener() {

@Override

public void onFailure(Exception e) {

e.printStackTrace();

}

});

}

}).addOnFailureListener(new OnFailureListener() {

@Override

public void onFailure(Exception e) {

e.printStackTrace();

}

});

}
Enter fullscreen mode Exit fullscreen mode

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
Make sure that languages are supported
Conclusion

In this article, we have learnt how to integrate Huawei ML kit service i.e. text translation(message) in Client Server messaging using Socket in Android application. You can check the desired result in the result section. Hoping Huawei ML kit capabilities are helpful to you as well, like this sample, you can make use of ML services as per your requirement.

Thank you so much for reading. I hope this article helps you to understand the integration of Huawei ML kit in Android application.

Reference

Huawei ML KitTraining video
Checkout in forum

Top comments (0)