More information like this, you can visit HUAWEI Developer Forum
Introduction
The Huawei Scan Kit offers versatile scanning, decoding, and generation capacities for bar code and QR code, enabling developers to quickly create the scans for QR code in apps.
Huawei can automatically detect and amplify long-distance or smaller scan codes via its long-range accumulation in the computer vision sector and automate the recognition of normal, complex barcode (example: reflection) scanning (such as dark light, smudge, blur and cylinder) scanning services. Scan Kit improves the performance rate and user experience of QR scanning code.
Zxing is a common third-party open-source SDK, it allows an Android device with imaging hardware (a built-in camera) to scan barcodes or 2-D graphical barcodes and retrieve the data encoded. It only carries out simple QR-code scanning operations and does not support complex scanning conditions, including high light, bend and deformation. However, the optimization effect is still not ideal, and many people will spend a lot of time on the optimization.
Let us now evaluate the Zxing and the Huawei HMS scan kit capabilities:
Note
In this article, I have scanned the code for 5 times and taken the best time captured.
Results may vary from device to device. I have used Huawei Y7p device for scanning, maintained similar condition for both HMS scan and Zxing.
Normal Scanning
{
"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"
}
When simple QR code is scanned from normal distance (around half feet), we have captured the time for decoding the code .
Huawei Scan kit took 0.68 seconds.
Zxing scanner took 1.38 seconds.
Result : HMS Scan kit wins
Scanning QR code at an angle
Let us scan the QR code at an angle more than 45 degrees from line of sight.
Huawei Scan kit took 0.657 seconds.
Zxing scanner took 1.27 seconds.
However, when we tried to capture at an angle more than 60 degrees, Zxing was not able to scan the code.
Result: HMS Scan kit wins
Scanning Complex Code:
Complex QR or bar code is too dense to decode. Let us see effectiveness of both the scanners.
Huawei scanner took 2.214 seconds when scanned from ideal distance (1.5 feet). However, if QR code is scanned from close distance it took 10.237 seconds. When QR code is scanned from distance more that 3 to 4 feet, it took 23.105 seconds.
ZXING scan took 19.10 seconds when scanned from ideal distance (1.5 feet). When scanned from too close or away from QR code, it was not able to able to scan it.
Result: HMS Scan kit wins.
Scanning code from long distance
Since Zxing does not have an automatic zoom-in optimisation, it is difficult to recognize code when the code is less than 20% of the frame.
The HMS Scan Kit has a pre-detection feature that can automatically amplify a long distance QR code even if the QR code cannot be detected by naked eyes.
HMS scan took 1.391 sec to detect when QR code is more 8 feet away.
Zxing failed to detect the code.
Result: HMS Scan kit wins
Implementation of HMS scan kit:
Prerequisite
Java JDK 1.8 or higher is recommended.
Android Studio is recommended.
Before developing an app, you will need to register as a HUAWEI developer. Refer to Register a HUAWEI ID.
Integrating app gallery connect SDK. Refer to AppGallery Connect Service Getting Started.
Development
1. Add the HMS scan kit dependencies in module-level build.gradle
Code:
implementation 'com.huawei.hms:scan:1.1.3.301'
2. To launch HMS default scanner
Code:
ScanUtil.startScan(this, REQUEST_CODE_SCAN_ONE, new HmsScanAnalyzerOptions.Creator().create());
3. Getting the scan result
Code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK || data == null) {
return;
}
endTime = System.currentTimeMillis();
//Default View
if (requestCode == REQUEST_CODE_SCAN_ONE) {
HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
if (obj != null) {
tvTimer.setText(String.valueOf((endTime-startTime) /1 000) + " sec");
}
}
Implementation of Zxing scan:
1. Add the Zxing scan dependencies in module-level build.gradle
Code:
implementation 'com.journeyapps:zxing-android-embedded:3.4.0'
2. To initialize QR code scanner
Code:
qrScan = new IntentIntegrator(this);
3. To launch the scanner
Code:
//initiating the qr code scan
qrScan.initiateScan();
4. Getting the scan result
Code:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK || data == null) {
return;
}
endTime = System.currentTimeMillis();
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
tvTimer.setText(String.valueOf((endTime-startTime)/1000) + " sec");
if (result != null) {
//if qrcode has nothing in it
if (result.getContents() == null) {
Toast.makeText(this, "Result Not Found", Toast.LENGTH_LONG).show();
} else {
//if qr contains data
try {
//converting the data to json
JSONObject obj = new JSONObject(result.getContents());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
Very nice and interesting article.
Just curious to know, If we scan in dark with mobile flash light, which takes less time?
Related
1. Background
Today's online games offer stunning effects and exhilarating gameplay, and user expectations for gaming have skyrocketed. Here, we'll talk about how large-screen games can be controlled on a mobile phone or tablet, via Nearby Service's Bluetooth- and Wi-Fi-based solution.
2. Applicable Scenarios
With Nearby Service, users are able to wirelessly transmit real-time data from the sensor on a mobile phone or tablet to a large-screen device, to enjoy gaming that is vast in scale, but remarkably easy to control. This controller function can be downloaded, simply by scanning the QR code displayed on the home page for the large-screen game, after which all gaming operations can be transmitted. Now we'll show you how transmission works for phone gyroscope data.
This solution enables users to benefit from a more powerful and cost-effective game controller, which does not require additional mobile data to be consumed, or even an Internet connection, meaning that it remains reliable at all times. In addition, it empowers the controller to discover, connect, and exchange data with nearby large-screen gaming devices, facilitating effortless multiplayer gaming.
3. Implementation Process
As shown below, the discoverer corresponds to the game controller, while the broadcaster corresponds to the large-screen gaming device. The implementation process is similar: broadcast and scanning -> connection setup -> data transmission -> disconnection. In the broadcast and scanning phase, Bluetooth low energy (BLE) broadcasting technology is used to discover devices. In the data transmission phase, high-speed transmission between devices can be implemented with ease, backed by the traditional P2P protocol.
{
"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"
}
4. Key Integration Steps and Code
(1) Broadcast.
Code:
<p style="line-height: 1.5em;">public void doStartBroadcast(View view) {
Context context = getApplicationContext();
mDiscoveryEngine = Nearby.getDiscoveryEngine(context);
BroadcastOption.Builder advBuilder = new BroadcastOption.Builder();
advBuilder.setPolicy(Policy.POLICY_STAR);
mDiscoveryEngine.startBroadcasting(myNameStr, myServiceId, mConnCb, advBuilder.build());
}
</p>
(2) Scan.
Code:
<p style="line-height: 1.5em;">public void doStartScan(View view) {
ScanOption.Builder discBuilder = new ScanOption.Builder();
discBuilder.setPolicy(Policy.POLICY_STAR);
mDiscoveryEngine.startScan(myServiceId, mDiscCb, discBuilder.build());
}
</p>
(3) Request a connection.
Code:
<p style="line-height: 1.5em;">private void connect(View view) {
mDiscoveryEngine.requestConnect(myNameStr, mEndpointId, mConnCb)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(SensorActivity.this,"connect Success",Toast.LENGTH_SHORT).show();
Log.d(TAG, "connect Success:");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Toast.makeText(SensorActivity.this,"connect Failure",Toast.LENGTH_SHORT).show();
Log.d(TAG, "connect Failure");
}
});
}
</p>
(4) Send and receive data.
Controller: Send the real-time data obtained by the phone gyroscope.
Code:
<p style="line-height: 1.5em;">private void sendData(Data bytesData){ Nearby.getTransferEngine(getApplicationContext()).sendData(mEndpointId, bytesData);}
</p>
Large-screen games: Receive data.
Code:
<p style="line-height: 1.5em;">private DataCallback mDataCb =
new DataCallback() {
@Override
public void onReceived(String string, Data data) {
Log.d(TAG, "onReceived, Data.Type = " + data.getType());
Log.d(TAG, "onReceived, string ======== " + string);
switch (data.getType()) {
case Data.Type.BYTES:
String str = new String(data.asBytes(), UTF_8);
receiveMessage(data);
break;
default:
Log.i(TAG, "the other Unknown data type, please check the uploaded file.");
return;
}
}
@Override
public void onTransferUpdate(String string, TransferStateUpdate update) {
Log.d(TAG, "onTransferUpdate.Status=======" + update.getStatus());
return;
}
}
};
</p>
Code:
<p style="line-height: 1.5em;">private void receiveMessage(Data data) {
msgStr = new String(data.asBytes(), UTF_8);
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
String dateStr = dateFormat.format(new Date());
tvData.append("\n" + dateStr + msgStr);
}
</p>
(5) Disconnect.
Code:
<p style="line-height: 1.5em;">private void disconnect(){
mDiscoveryEngine.disconnect(mEndpointId);
}
</p>
5. Effects
Due to hardware limitations, we used two mobile phones for the test, with one serving as the controller to send real-time data for phone gyroscope, and the other as the large-screen gaming device to receive the data. After the data is received, it is calculated to obtain the game controller operations.
When the distance between the two devices is about three meters, the comparison between the transmitted and received data is as follows:
When two devices are close to each other (for example, approximately three or four meters apart), the latency for data transmission is generally less than one second, which can be regarded as real-time data. Even when the distance is changing, the service remains user-friendly.
Note: Currently, when there are no obstacles obstructing the Bluetooth signal from the two devices, data transmission remains smooth within seven meters. The Bluetooth connection will likely be inconsistent when the distance exceeds eight meters, and non-existent beyond ten meters.
6. Precautions
(1) In this example, you would need to enter the names of both devices for the connection. In the broadcast and scanning phase, you can display the list of discovered devices and allow users to select the devices to be connected.
(2) The example above makes use of the point-to-point connection policy, which supports a 1-to-N or star-shaped connection topology. You can also use the point-to-point connection policy that supports an M-to-N or cluster-shaped connection topology, and policy that supports a 1-to-1 connection topology. For details about the application scenarios of these three policies, please refer to Nearby Service-Broadcast and Scanning.
(3) The data transmitted in this example is in byte sequence (BYTES), in which the data size cannot exceed 32 KB. You can also use two other data types, as needed: FILE and STREAM.
(4) In this example, unprocessed phone gyroscope data is sent. You can control the game operations by calculating the data.
(5) In this example, there is some amount of latency when data is sent and received. The latency is for reference only, and should not be regarded as the standard of performance for Nearby Service.
BackgroundThe real-time onscreen subtitle is a must-have function in an ordinary video app. However, developing such a function can prove costly for small- and medium-sized developers. And even when implemented, speech recognition is often prone to inaccuracy. Fortunately, there's a better way — HUAWEI ML Kit, which is remarkably easy to integrate, and makes real-time transcription an absolute breeze!
Introduction to ML KitML Kit allows your app to leverage Huawei's longstanding machine learning prowess to apply cutting-edge artificial intelligence (AI) across a wide range of contexts. With Huawei's expertise built in, ML Kit is able to provide a broad array of easy-to-use machine learning capabilities, which serve as the building blocks for tomorrow's cutting-edge AI apps. ML Kit capabilities include those related to:
Text (including text recognition, document recognition, and ID card recognition)
Language/Voice (such as real-time/on-device translation, automatic speech recognition, and real-time transcription)
Image (such as image classification, object detection and tracking, and landmark recognition)
Face/Body (such as face detection, skeleton detection, liveness detection, and face verification)
Natural language processing (text embedding)
Custom model (including the on-device inference framework and model development tool)
Real-time transcription is required to implement the function mentioned above. Let's take a look at how this works in practice:
{
"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"
}
Now let's move on to how to integrate this service.
Integrating Real-Time TranscriptionSteps
Registering as a Huawei developer on HUAWEI Developers
Creating an app
Create an app in AppGallery Connect. For details, see Getting Started with Android.
We have provided some screenshots for your reference:
3. Enabling ML Kit
4. Integrating the HMS Core SDK.
Add the AppGallery Connect configuration file by completing the steps below:
Download and copy the agconnect-service.json file to the app directory of your Android Studio project.
Call setApiKey during app initialization.
To learn more, go to Adding the AppGallery Connect Configuration File.
5.Configuring the maven repository address
Add build dependencies.
Import the real-time transcription SDK.
Code:
implementation 'com.huawei.hms:ml-computer-voice-realtimetranscription:2.2.0.300'
Add the AppGallery Connect plugin configuration.
Method 1: Add the following information under the declaration in the file header:
Code:
apply plugin: 'com.huawei.agconnect'
Method 2: Add the plugin configuration in the plugins block.
Code:
plugins {
id 'com.android.application'
// Add the following configuration:
id 'com.huawei.agconnect'
}
Please refer to Integrating the Real-Time Transcription SDK to learn more.
Setting the cloud authentication information
When using on-cloud services of ML Kit, you can set the API key or access token (recommended) in either of the following ways:
Access token
You can use the following API to initialize the access token when the app is started. The access token does not need to be set again once initialized.
MLApplication.getInstance().setAccessToken("your access token");
API key
You can use the following API to initialize the API key when the app is started. The API key does not need to be set again once initialized.
MLApplication.getInstance().setApiKey("your ApiKey");
For details, see Notes on Using Cloud Authentication Information.
Code Development
Create and configure a speech recognizer.
Code:
MLSpeechRealTimeTranscriptionConfig config = new MLSpeechRealTimeTranscriptionConfig.Factory()
// Set the language. Currently, this service supports Mandarin Chinese, English, and French.
.setLanguage(MLSpeechRealTimeTranscriptionConstants.LAN_ZH_CN)
// Punctuate the text recognized from the speech.
.enablePunctuation(true)
// Set the sentence offset.
.enableSentenceTimeOffset(true)
// Set the word offset.
.enableWordTimeOffset(true)
// Set the application scenario. MLSpeechRealTimeTranscriptionConstants.SCENES_SHOPPING indicates shopping, which is supported only for Chinese. Under this scenario, recognition for the name of Huawei products has been optimized.
.setScenes(MLSpeechRealTimeTranscriptionConstants.SCENES_SHOPPING)
.create();
MLSpeechRealTimeTranscription mSpeechRecognizer = MLSpeechRealTimeTranscription.getInstance();
Create a speech recognition result listener callback.
Code:
// Use the callback to implement the MLSpeechRealTimeTranscriptionListener API and methods in the API.
protected class SpeechRecognitionListener implements MLSpeechRealTimeTranscriptionListener{
@Override
public void onStartListening() {
// The recorder starts to receive speech.
}
@Override
public void onStartingOfSpeech() {
// The user starts to speak, that is, the speech recognizer detects that the user starts to speak.
}
@Override
public void onVoiceDataReceived(byte[] data, float energy, Bundle bundle) {
// Return the original PCM stream and audio power to the user. This API is not running in the main thread, and the return result is processed in a sub-thread.
}
@Override
public void onRecognizingResults(Bundle partialResults) {
// Receive the recognized text from MLSpeechRealTimeTranscription.
}
@Override
public void onError(int error, String errorMessage) {
// Called when an error occurs in recognition.
}
@Override
public void onState(int state,Bundle params) {
// Notify the app of the status change.
}
}
The recognition result can be obtained from the listener callbacks, including onRecognizingResults. Design the UI content according to the obtained results. For example, display the text transcribed from the input speech.
Bind the speech recognizer.
Code:
mSpeechRecognizer.setRealTimeTranscriptionListener(new SpeechRecognitionListener());
Call startRecognizing to start speech recognition.
Code:
mSpeechRecognizer.startRecognizing(config);
Release resources after recognition is complete.
Code:
if (mSpeechRecognizer!= null) {
mSpeechRecognizer.destroy();
}
(Optional) Obtain the list of supported languages.
Code:
MLSpeechRealTimeTranscription.getInstance()
.getLanguages(new MLSpeechRealTimeTranscription.LanguageCallback() {
@Override
public void onResult(List<String> result) {
Log.i(TAG, "support languages==" + result.toString());
}
@Override
public void onError(int errorCode, String errorMsg) {
Log.e(TAG, "errorCode:" + errorCode + "errorMsg:" + errorMsg);
}
});
We have finished integration here, so let's test it out on a simple screen.
Tap START RECORDING. The text recognized from the input speech will display in the lower portion of the screen.
We've now built a simple audio transcription function.
Eager to build a fancier UI, with stunning animations, and other effects? By all means, take your shot!
For reference:Real-Time Transcription
Sample Code for ML Kit
To learn more, please visit:
HUAWEI Developers official website
Development Guide
Reddit to join developer discussions
GitHub or Gitee to download the demo and sample code
Stack Overflow to solve integration problems
Follow our official account for the latest HMS Core-related news and updates.
Original Source
View attachment Featured image.jpg
As the start of the new academic year approaches, many college students will be leaving their parents to start college life. However, a lack of experience makes it easy for college students to become victims of electronic fraud such as phone scams.
The start of the new academic year is often a period of time that sees an uptick in phone scams, especially those targeting college students. Some scammers trick students to download and register an account on malicious financial apps embedded with viruses and Trojan horses or ones that imitate legitimate apps. With such malicious apps installed on students' phones, scammers are able to steal students' sensitive data, such as bank card numbers and passwords. Some scammers trick students, by offering them small gifts or coupons, to scan QR codes which then direct them to pages that ask users to enter their personal information, such as their phone number and address. Once a student has done this, they will receive a large number of fraudulent calls and junk SMS messages from then on. If the students scan QR codes linking to phishing websites, their personal data may be leaked and sold for malicious purposes. Some scammers even lie about offering students scholarships or grants, in order to trick them into visiting phishing websites and entering their bank account numbers and passwords, causing significant financial losses to such students.
{
"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 deal with the ever-changing tricks of fraudsters, an app needs to detect phishing websites, malicious apps, and other risks and remind users to be on the lookout for such risks with in-app tips, in order to keep users and their data safe. So, is there a one-stop service that can enhance app security from multiple dimensions? Fortunately, HMS Core Safety Detect can help developers quickly build security capabilities into their apps, and help vulnerable user groups such as college students safeguard their information and property.
The AppsCheck API in Safety Detect allows your app to obtain a list of malicious apps installed on a user's device. The API can identify 99% of malicious apps and detect unknown threats based on app behavior. Your app can then use this information to determine whether to restrict users from performing in-app payments and other sensitive operations.
The URLCheck API in Safety Detect checks whether an in-app URL is malicious. If the URL is determined to be malicious, the app can warn the user of the risk or block the URL.
Safety Detect also provides capabilities to check system integrity and detect fake users, helping developers quickly improve their app security. The integration process is straightforward, which I'll describe below.
Demo
Integration ProcedurePreparationsYou can follow the instructions here to prepare for the integration.
Using the AppsCheck APIYou can directly call getMaliciousAppsList of SafetyDetectClient to obtain a list of malicious apps. The sample code is as follows:
Code:
private void invokeGetMaliciousApps() {
SafetyDetectClient appsCheckClient = SafetyDetect.getClient(MainActivity.this);
Task task = appsCheckClient.getMaliciousAppsList();
task.addOnSuccessListener(new OnSuccessListener<MaliciousAppsListResp>() {
@Override
public void onSuccess(MaliciousAppsListResp maliciousAppsListResp) {
// Indicates that communication with the service was successful.
// Use resp.getMaliciousApps() to obtain a list of malicious apps.
List<MaliciousAppsData> appsDataList = maliciousAppsListResp.getMaliciousAppsList();
// Indicates that the list of malicious apps was successfully obtained.
if(maliciousAppsListResp.getRtnCode() == CommonCode.OK) {
if (appsDataList.isEmpty()) {
// Indicates that no known malicious apps were detected.
Log.i(TAG, "There are no known potentially malicious apps installed.");
} else {
Log.i(TAG, "Potentially malicious apps are installed!");
for (MaliciousAppsData maliciousApp : appsDataList) {
Log.i(TAG, "Information about a malicious app:");
// Use getApkPackageName() to obtain the APK name of the malicious app.
Log.i(TAG, "APK: " + maliciousApp.getApkPackageName());
// Use getApkSha256() to obtain the APK SHA-256 of the malicious app.
Log.i(TAG, "SHA-256: " + maliciousApp.getApkSha256());
// Use getApkCategory() to obtain the category of the malicious app.
// Categories are defined in AppsCheckConstants.
Log.i(TAG, "Category: " + maliciousApp.getApkCategory());
}
}
}else{
Log.e(TAG,"getMaliciousAppsList failed: "+maliciousAppsListResp.getErrorReason());
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// An error occurred during communication with the service.
if (e instanceof ApiException) {
// An error with the HMS API contains some
// additional details.
ApiException apiException = (ApiException) e;
// You can retrieve the status code using the apiException.getStatusCode() method.
Log.e(TAG, "Error: " + SafetyDetectStatusCodes.getStatusCodeString(apiException.getStatusCode()) + ": " + apiException.getStatusMessage());
} else {
// A different, unknown type of error occurred.
Log.e(TAG, "ERROR: " + e.getMessage());
}
}
});
}
Using the URLCheck API1. Initialize the URLCheck API.
Before using the URLCheck API, you must call the initUrlCheck method to initialize the API. The sample code is as follows:
Code:
SafetyDetectClient client = SafetyDetect.getClient(getActivity());
client.initUrlCheck();
2. Request a URL check.
You can pass target threat types to the URLCheck API as parameters. The constants in the UrlCheckThreat class include the current supported threat types.
Code:
public class UrlCheckThreat {
// URLs of this type are marked as URLs of pages containing potentially malicious apps (such as home page tampering URLs, Trojan-infected URLs, and malicious app download URLs).
public static final int MALWARE = 1;
// URLs of this type are marked as phishing and spoofing URLs.
public static final int PHISHING = 3;
}
a. Initiate a URL check request.
The URL to be checked contains the protocol, host, and path but does not contain the query parameter. The sample code is as follows:
Code:
String url = "https://developer.huawei.com/consumer/cn/";
SafetyDetect.getClient(this).urlCheck(url, appId, UrlCheckThreat.MALWARE, UrlCheckThreat.PHISHING).addOnSuccessListener(this, new OnSuccessListener<UrlCheckResponse >(){
@Override
public void onSuccess(UrlCheckResponse urlResponse) {
if (urlResponse.getUrlCheckResponse().isEmpty()) {
// No threat exists.
} else {
// Threats exist.
}
}
}).addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// An error occurred during communication with the service.
if (e instanceof ApiException) {
// HMS Core (APK) error code and corresponding error description.
ApiException apiException = (ApiException) e;
Log.d(TAG, "Error: " + CommonStatusCodes.getStatusCodeString(apiException.getStatusCode()));
// Note: If the status code is SafetyDetectStatusCode.CHECK_WITHOUT_INIT,
// you did not call the initUrlCheck() method or you have initiated a URL check request before the call is completed.
// If an internal error occurs during the initialization, you need to call the initUrlCheck() method again to initialize the API.
} else {
// An unknown exception occurred.
Log.d(TAG, "Error: " + e.getMessage());
}
}
});
b. Call the getUrlCheckResponse method of the returned UrlCheckResponse object to obtain the URL check result.
The result contains List<UrlCheckThreat>, which includes the detected URL threat type. If the list is empty, no threat is detected. Otherwise, you can call getUrlCheckResult in UrlCheckThreat to obtain the specific threat code. The sample code is as follows:
Code:
final EditText testRes = getActivity().findViewById(R.id.fg_call_urlResult);
List<UrlCheckThreat> list = urlCheckResponse.getUrlCheckResponse();
if (list.isEmpty()) {
testRes.setText("ok");
}
else{
for (UrlCheckThreat threat : list) {
int type = threat.getUrlCheckResult();
}
}
3. Close the URL check session.
If your app does not need to call the URLCheck API anymore or will not need to for a while, you can call the shutdownUrlCheck method to close the URL check session and release relevant resources.
Code:
SafetyDetect.getClient(this).shutdownUrlCheck();
ConclusionElectronic fraud such as phone scams are constantly evolving and becoming more and more difficult to prevent, bringing great challenges to both developers and users. To combat such risks, developers must utilize technical means to identify phishing websites, malicious apps, and other risks, in order to safeguard users' personal information and property.
In this article, I demonstrated how HMS Core Safety Detect can be used to effectively combat electronic fraud. The whole integration process is straightforward and cost-efficient, and is a quick and effective way to build comprehensive security capabilities into an app.
During workouts, users expect to be able to track their status and data in real time within the health or fitness app on their phone. Huawei phone users can link a piece of equipment, like a treadmill or spinner bike, via the Huawei Health app, and start and track their workout within the app. As a fitness and health app developer, you can read activity records from the Huawei Health app, and display the records in your app. It is even possible to control the workout status directly within your app, and obtain real-time activity data, without having to redirect users to the Huawei Health app, which helps users conveniently track their workout and greatly enhances the user experience. Here is how.
HMS Core Health Kit provides a wide range of capabilities for fitness and health app developers. Its extended capabilities open up a wealth of real time activity and health data and solutions specific to different scenarios. For example, after integrating the extended capabilities, you can call the APIs for starting, pausing, resuming, and stopping activities, to control activity status directly within your app, without redirecting users to the Huawei Health app. The Huawei Health app runs unobtrusively in the background throughout this entire process.
The extended capabilities also offer APIs for obtaining and halting the collection of real-time workout data. To prevent data loss, your app should call the API for obtaining real-time data before the workout starts, and avoid calling the API for halting the collection of real-time data before the workout ends. If the user links their phone with a Huawei wearable device via the Huawei Health app, the workout status in your app will be synched to the wearable device. This means that the wearable device will automatically display the workout screen when the user starts a workout in your app, and will stop displaying it as soon as the workout is complete. Make sure that you have applied for the right scopes from Huawei and obtained the authorization from users before API calling. Otherwise, API calling will fail. The following workouts are currently supported: outdoor walking, outdoor running, outdoor cycling, indoor running (on a treadmill), elliptical machine, rowing machine, and indoor cycling.
{
"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"
}
Redirecting to the device pairing screen
Demo
PreparationsApplying for Health KitBefore applying for Health Kit, you will need to apply for Account Kit first.
Integrating the HMS Core SDKBefore integrating the Health SDK, integrate the Account SDK first.
Before getting started, you need to integrate the HMS Core SDK into your app using Android Studio. Make sure that you use Android Studio V3.3.2 or later during the integration of Health Kit.
Development ProcedureStarting Obtaining Real-time Activity Data1. Call the registerSportData method of the HiHealthDataStore object to start obtaining real time activity data.
2. Check the returned result through the request parameter HiSportDataCallback.
The sample code is as follows:
Code:
HiHealthDataStore.registerSportData(context, new HiSportDataCallback() {
@Override
public void onResult(int resultCode) {
// API calling result.
Log.i(TAG, "registerSportData onResult resultCode:" + resultCode);
}
@Override
public void onDataChanged(int state, Bundle bundle) {
// Real-time data change callback.
Log.i(TAG, "registerSportData onChange state: " + state);
StringBuffer stringBuffer = new StringBuffer("");
if (state == HiHealthKitConstant.SPORT_STATUS_RUNNING) {
Log.i(TAG, "heart rate : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_HEARTRATE));
Log.i(TAG, "distance : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_DISTANCE));
Log.i(TAG, "duration : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_DURATION));
Log.i(TAG, "calorie : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_CALORIE));
Log.i(TAG, "totalSteps : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_TOTAL_STEPS));
Log.i(TAG, "totalCreep : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_TOTAL_CREEP));
Log.i(TAG, "totalDescent : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_TOTAL_DESCENT));
}
}
});
Stopping Obtaining Real-time Activity Data1. Call the unregisterSportData method of the HiHealthDataStore object to stop obtaining the real time activity data.
2. Check the returned result through the request parameter HiSportDataCallback.
The sample code is as follows:
Code:
HiHealthDataStore.unregisterSportData(context, new HiSportDataCallback() {
JSONObject jsonResult
@Override
public void onResult(int resultCode) {
// API calling result.
Log.i(TAG, "unregisterSportData onResult resultCode:" + resultCode);
}
@Override
public void onDataChanged(int state, Bundle bundle) {
// The API is not called at the moment.
}
});
Starting an Activity According to the Activity Type1. Call the startSport method of the HiHealthDataStore object to start a specific type of activity.
2. Use the ResultCallback object as a request parameter to get the query result.
The sample code is as follows:
Code:
// Outdoor running.
int sportType = HiHealthKitConstant.SPORT_TYPE_RUN;
HiHealthDataStore.startSport(context, sportType, new ResultCallback() {
@Override
public void onResult(int resultCode, Object message) {
if (resultCode == HiHealthError.SUCCESS) {
Log.i(TAG, "start sport success");
}
}
});
3. For activities that depend on equipment like treadmills, rowing machines, elliptical machines, and stationary bikes, you will need to first check whether the relevant equipment has been paired in the Huawei Health app before starting the activity. The following uses a rowing machine as an example.
If there is one rowing machine paired, this machine will be connected by default, and the activity will then start in the background.
If the app is paired with more than one rowing machines, a pop-up window will display prompting the user to select a machine. After the user makes their choice, the window will disappear and the workout will start in the background.
If the app is not paired with any rowing machine, the user will be redirected to the device pairing screen in the Huawei Health app, before being returned to your app. The workout will then start in the background.
Starting an Activity Based on the Device Information1. Call the startSportEx method of the HiHealthDataStore object, and pass the StartSportParam parameter for starting the activity. You can control whether to start the activity in the foreground or in the background by setting CharacteristicConstant.SportModeType.
2. Use the ResultCallback object as a request parameter to get the activity starting result.
The sample code is as follows:
Code:
// The following takes the rowing machine as an example.
// MAC address, with every two digits separated by a colon (:), for example, 11:22:33:44:55:66.
String macAddress = "11:22:33:44:55:66" ;
// Whether FTMP is supported. 0: no; 1: yes.
int isSupportedFtmp = CharacteristicConstant.FtmpType.FTMP_SUPPORTED.getFtmpTypeValue();
// Device type: rowing machine.
int deviceType = CharacteristicConstant.DeviceType.TYPE_ROWER_INDEX.getDeviceTypeValue();
// Activity type: rowing machine.
int sportType = CharacteristicConstant.EnhanceSportType.SPORT_TYPE_ROW_MACHINE.getEnhanceSportTypeValue();
// Construct startup parameters for device connection and activity control.
StartSportParam param = new StartSportParam(macAddress, isSupportedFtmp, deviceType, sportType);
// Whether to start the activity in the foreground (0) or background (1).
param.putInt(HiHealthDataKey.IS_BACKGROUND,
CharacteristicConstant.SportModeType.BACKGROUND_SPORT_MODE.getType());
HiHealthDataStore.startSportEx(mContext, param, new ResultCallback() {
@Override
public void onResult(int resultCode, Object message) {
if (resultCode == HiHealthError.SUCCESS) {
Log.i(TAG, "start sportEx success");
}
}
});
Stopping an Activity1. Call the stopSport method of the HiHealthDataStore object to stop a specific type of activity. Note that you cannot use this method to stop activities started in the foreground.
2. Use the ResultCallback object as a request parameter to get the query result.
The sample code is as follows:
Code:
HiHealthDataStore.stopSport(context, new ResultCallback() {
@Override
public void onResult(int resultCode, Object message) {
if (resultCode == HiHealthError.SUCCESS) {
Log.i(TAG, "stop sport success");
}
}
});
ConclusionHuawei phone users can use the Huawei Health app to bind wearable devices, start a workout and control their workout status, and track their workouts over time. When developing a fitness and health app, you can harness the capabilities in Health Kit and the Huawei Health app to get the best of all worlds: easy workout management free of annoying redirections. By calling the APIs provided by the kit's extended capabilities, you will be able to start, pause, resume, and stop workouts directly in your app, or obtain real time workout data from the Huawei Health app and display it in your app, with Huawei Health running in the background. This will considerably enhance the user experience, and make your fitness and health app much more appealing to a wider audience.
ReferencesHMS Core Health Kit Development Guide
Bundle Keys for Real-time Activity
Applying for the HUAWEI ID Service
I recently came across an article saying that barcodes and barcode readers have become a mainstay of today's economies and our lives in general, since they were introduced in the 1970s.
So, I decided to test how true this is by seeing how often I come across barcode readers in a typical day of mine. And — surprise surprise — they turned out to be more important than I thought.
A Reader's Day in My LifeRight after I left my home in the morning, I came across a bike for hire and used a bike sharing app to scan the QR code on the bike to unlock it. When I finally got to work, I scanned the bike's code again to lock it and complete the journey.
At lunch, I went to a café, sat down, and scanned the barcode on the table to order some lunch. After filling myself up, I went to the counter and scanned the QR code on the wall to pay.
And after work, before I went home, I went to my local collection point to pick up the smartwatch I'd recently bought. It was here where I saw the staff struggling to scan and record the details of the many packages they were handling. When I finally got home and had dinner, there was one last barcode to scan for the day. That was the QR code for the brand-new smartwatch, which was needed for linking the device with an app on my phone.
Overcoming Obstacles for Barcode ReadersThat said, scanning barcodes is not as easy as it sounds because the scanning experience encountered several challenges:
First, poor-quality barcodes made recognizing barcodes a challenge. Barcodes on the bike and table were smudged due to daily wear and tear, which is common in a public space.
Second, the placement of codes is not ideal. There was an awkward moment when I went to the counter to pay for my lunch, and the payment code was stuck on the wall right next to a person who thought I was trying to secretly take a picture of him.
Third is slow and rigid barcode scanning. When I went to the collection point, it was clear that the efficiency of the sorters was let down by their readers, which were unable to scan multiple barcodes at once.
Fourth, different barcode formats mean that the scanning mode must be switched.
So, in the face of all these challenges, I decided to develop my own reader. After doing some research and testing, I settled on HMS Core Scan Kit, because this kit utilizes computer vision technologies to ensure that it can recognize a hard-to-read barcode caused by factors including dirt, light reflection, and more. The kit can automatically zoom in on a barcode image from a distance so that the barcode can be easily identified, by using the deep learning algorithm model. The kit supports multi-scanning of five different barcodes at once, for faster recording of barcode information. And the kit supports 13 barcode formats, covering those commonly adopted in various scenarios.
{
"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"
}
Aside from these advantages, I also found that the kit supports customization of the scanning UI, analysis of barcode content in 12 kinds of scenarios for extracting structured data, two SDKs (1.1 MB and 3.3 MB respectively), and four different call modes. An Android app can be integrated with the kit in just five lines of code. And of the modes available, I chose the Default View mode for my app. Let's have a look at how this works.
Service Process of the Solution
Specifically speaking:
1. A user opens an app and sends a barcode scanning request.
2. The app checks whether it has the camera permission.
3. When the app has obtained the permission, the app calls the startScan API to launch the barcode scanning UI.
4. The HMS Core SDK checks whether the UI is successfully displayed.
5. The HMS Core SDK calls onActivityResult to obtain the scanning result.
6. The app obtains the scanning result according to the scanning status (RESULT_CODE). If the result is SUCCESS, the app returns the scanning result to the user; if the result is ERROR_NO_READ_PERMISSION, the app needs to apply for the file read permission and enters the Default View mode again.
7. The app encapsulates the scanning result and sends it to the user.
Development ProcedureMaking Preparations1. Install Android Studio 3.6.1 or later.
2. Install JDK 1.8.211 or later.
3. Make the following app configurations:
minSdkVersion: 19 or later
targetSdkVersion: 33
compileSdkVersion: 31
Gradle version: 4.6 or later
4. Install the SDK Platform 21 or later.
5. Register as a developer.
6. Create a project and an app in AppGallery Connect.
7. Generate a signing certificate fingerprint, which is used to verify the authenticity of an app.
8. Go to AppGallery Connect to add the fingerprint in the SHA-256 certificate fingerprint field, as marked in the figure below.
9. Integrate the HMS Core SDK with the Android Studio project.
10. Configure obfuscation scripts so that the SDK will not be obfuscated.
11. Integrate Scan Kit via HMS Toolkit. For details, click here.
12. Declare necessary permissions in the AndroidManifest.xml file.
Developing the Scanning Function1. Set the scanning parameters, which is an optional step.
Scan Kit supports 13 barcode formats in total. You can add configurations so that Scan Kit will scan only the barcodes of your desired formats, increasing the scanning speed. For example, when only the QR code and DataMatrix code need to be scanned, follow the code below to construct the HmsScanAnalyzerOptions object.
When there is no specified format of the barcodes to be scanned, this object is not required. 1 is one of the parameter values for the scanning UI titles, corresponding to the var1 parameter in setViewType.
Code:
// QRCODE_SCAN_TYPE and DATAMATRIX_SCAN_TYPE indicate that Scan Kit will support only the barcodes in the QR code and DataMatrix formats. setViewType is used to set the scanning UI title. 0 is the default value, indicating title Scan QR code/barcode, and 1 indicates title Scan QR code. setErrorCheck is used to set the error listener. true indicates that the scanning UI is exited upon detection of an error; false indicates that the scanning UI is exited upon detection of the scanning result, without reporting the error.
HmsScanAnalyzerOptions options = new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.QRCODE_SCAN_TYPE, HmsScan.DATAMATRIX_SCAN_TYPE).setViewType(1).setErrorCheck(true).create();
2. Call startScan of ScanUtil to start the scanning UI of the Default View mode, where a user can choose to use the camera to scan a barcode or go to the phone's album and select an image to scan.
REQUEST_CODE_SCAN_ONE: request ID, corresponding to the requestCode parameter of the onActivityResult method. This parameter is used to check whether the call to onActivityResult is from the scanning result callback of Scan Kit. If requestCode in the onActivityResult method is exactly the request ID defined here, the scanning result is successfully obtained from Scan Kit.
Set options to null when there is a need to scan barcodes in all formats supported by the kit.
Code:
ScanUtil.startScan(this, REQUEST_CODE_SCAN_ONE, options);
3. Receive the scanning result using the callback API, regardless of whether the scanned object is captured by the camera or from an image in the album.
Call the onActivityResult method of the activity to obtain the intent, in which the scanning result object HmsScan is encapsulated. RESULT describes how to obtain intent parameters.
If the value of requestCode is the same as that of REQUEST_CODE_SCAN_ONE defined in step 2, the received intent comes from Scan Kit.
Obtain the code scanning status through RESULT_CODE in the intent.
Use RESULT in the intent to obtain the object of the HmsScan class.
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK || data == null) {
return;
}
if (requestCode == REQUEST_CODE_SCAN_ONE) {
// Input an image for scanning and return the result.
int errorCode = data.getIntExtra(ScanUtil.RESULT_CODE, ScanUtil.SUCCESS);
if (errorCode == ScanUtil.SUCCESS) {
Object obj = data.getParcelableExtra(ScanUtil.RESULT);
if (obj != null) {
// Display the scanning result.
...
}
}
if (errorCode == ScanUtil.ERROR_NO_READ_PERMISSION) {
// The file read permission is not assigned. Apply for the permission.
...
}
}
}
Then — Boom! The barcode reader is all set and ready. I gave it a spin last week and everything seemed to be working well.
TakeawayBarcodes are everywhere these days, so it's important to carry a barcode reader at all times. This signals a fantastic opportunity for app developers.
The ideal barcode reader will support different barcode formats, be capable of identifying poor-quality barcodes in challenging environments, and support multi-scanning of barcodes at the same time.
As challenging as it sounds, HMS Core Scan Kit is the perfect companion. Computer vision techs, deep learning algorithm, support for multiple and continuous barcode scanning… With all these features, together with its easy-to-use and lightweight SDKs and flexible call modes, the kit gives developers and users all they'll ever need from a barcode reader app.