Symptom
After an image drawn by the canvas component is saved to the album, the image cannot be displayed in the album. Only a black background image is displayed.
The image with green background in the following figure is drawn by the canvas component.
{
"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"
}
After the image is saved to the album, the display result is as shown in the following figure.
Cause Analysis
Huawei Quick App Center creates a ctx object each time when it calls the getContext method, and therefore different ctx objects will be returned. Some of these ctx objects are empty. An empty ctx object may be obtained in a random selection. As a result, the image saved may have no content. The code is as follows:
Code for using canvas to draw an image:
HTML:
pic() {
var test = this.$element("canvas");
var ctx = test.getContext("2d");
var img = new Image();
img.src = "http://www.huawei.com/Assets/CBG/img/logo.png";
img.onload = function () {
console.log("Image loaded successfully");
ctx.drawImage(img, 10, 10, 300, 300, );
}
img.onerror = function () {
console.log("Failed to load the image");
}
},
Code for saving the image:
HTML:
save() {
var test = this.$element("canvas");
test.toTempFilePath({
fileType: "jpg",
quality: 1.0,
success: (data) => {
console.log(`Canvas toTempFilePath success ${data.uri}`)
console.log(`Canvas toTempFilePath success ${data.tempFilePath}`)
media.saveToPhotosAlbum({
uri: data.uri,
success: function (ret) {
console.log("save success: ");
},
fail: function (data, code) {
console.log("handling fail, code=" + code);
}
})
},
fail: (data) => {
console.log('Canvas toTempFilePath data =' + data);
},
complete: () => {
console.log('Canvas toTempFilePath complete.');
}
})
}
Solution
Define ctx as a global variable and check whether it is empty. Assign an initial value to an empty ctx.
Optimized code:
HTML:
var ctx; // Define a global variable.
pic() {
if (!ctx) {// Check whether a ctx object is empty. If it is empty, assign the 2d value to it.
var test = this.$element("canvas");
var tt = test.getContext("2d");
ctx = tt;
}
var img = new Image();
img.src = "http://www.huawei.com/Assets/CBG/img/logo.png";
img.onload = function () {
console.log("Image loaded successfully");
ctx.drawImage(img, 10, 10, 300, 300, );
}
img.onerror = function () {
console.log("Failed to load the image");
}
}
Related
{
"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"
}
Start your project
First of all, install eclipse and the android stuff
Then create a new android project, in my case its called com.xda.tutorialscript
Then we need to create the required layout items
Edit res->layout->main.xml
Add a Edittext, Button and TextView
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
androidrientation=”vertical” >
<EditText
android:id=”@+input/input1″
android:layout_height=”wrap_content”
android:layout_width=”fill_parent”
/>
<Button
android:id=”@+button/run”
android:layout_height=”wrap_content”
android:layout_width=”wrap_content”
android:text=”Go”
/>
<TextView
android:id=”@+text/text1″
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Output” />
</LinearLayout>
After that we need to create the code for the root command, bellow there is my version with output treatment and input of a textview to be used as input also, by that you can use the same command on lots of activities and have the output on the textview
// Root Access script runner
void execCommandLine(String command, TextView tv)
{
Runtime runtime = Runtime.getRuntime();
Process proc = null;
OutputStreamWriter osw = null;
// Running the Script
try
{
proc = runtime.exec(“su”);
osw = new OutputStreamWriter(proc.getOutputStream());
osw.write(command);
osw.flush();
osw.close();
}
// If return error
catch (IOException ex)
{
// Log error
Log.e(“execCommandLine()”, “Command resulted in an IO Exception: ” + command);
return;
}
// Try to close the process
finally
{
if (osw != null)
{
try
{
osw.close();
}
catch (IOException e){}
}
}
try
{
proc.waitFor();
}
catch (InterruptedException e){}
// Display on screen if error
if (proc.exitValue() != 0)
{
Log.e(“execCommandLine()”, “Command returned error: ” + command + “\n Exit code: ” + proc.exitValue());
AlertDialog.Builder builder = new AlertDialog.Builder(ScriptrunActivity.this);
builder.setMessage(command + “\nWas not executed sucessfully!”);
builder.setNeutralButton(“OK”, null);
AlertDialog dialog = builder.create();
dialog.setTitle(“Script Error”);
dialog.show();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
try {
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String exit = output.toString();
if(exit != null && exit.length() == 0) {
exit = “Command executed Successfully but no output was generated”;
}
tv.setText(exit);
}
After that we have to create a button to grab the text inside the textedit and use as a command
// Button
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button go = (Button) findViewById(R.button.run);
go.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Get ID’s
TextView tv = (TextView)findViewById(R.text.text1);
EditText text_id = (EditText)findViewById(R.input.input1);
String input = text_id.getText().toString();
execCommandLine(input, tv);
}
});
A simple explanation of what happens:
The findViewById is used to get the id of the layout item, so we can use it later and by that we declare the textview id ( to be used as input of the execcommand) and button id
Then we get the text from the input1 that is the textedit and transform it to a string to be used in the execCommandLine
And for last we use the execCommandLine
The string input will be used and the output will be transformed from inputstream to string and sent to the textview choosed
Hope you all enjoyed this Do it Your Self
madteam.co
I suggest Code Tags.
thanks
Mre information like this, you can visit HUAWEI Developer Forum
Do you want to test a web page whether is functional or not before providing solutions to CPs you can use Quick App IDE for testing just in a few steps:
1) Create a new project by using File > New Project > New QuickApp Project... direction. Enter App Name, Package Name and select "Hello World" template.
{
"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"
}
2) Open "hello.ux" file folder and paste following script. You only need to change loadUrl adress that you want to test e.g. https://developer.huawei.com/consumer/en/doc/
Code:
template>
<div class="doc-page">
<!-- Replace the link to the HTML5 app -->
<web class="web-page" src="{{loadUrl}}" trustedurl="{{list}}" onpagestart="onPageStart" onpagefinish="onPageFinish"
onmessage="onMessage" ontitlereceive="onTitleReceive"
onerror="onError" id="web"
supportzoom="{{supportZoom}}"
wideviewport="{{wideViewport}}}"
overviewmodeinload="{{overViewModeLoad}}"
useragent="{{ua}}"
allowthirdpartycookies="{{allowThirdPartyCookies}}">
</web>
</div>
</template>
<style>
.doc-page {
flex-direction: column;
flex-direction: column;
justify-content: center;
align-content: center;
align-items: center;
width: 100%;
height: 100%;
position: fixed;
}
.web-page {
width: 100%;
height: 100%;
}
</style>
<script>
import router from "@system.router";
export default {
props: ['websrc'],
data: {
title: "",
// TODO Replace the link to the H5 app
loadUrl: "https://developer.huawei.com/consumer/en/doc/",
// Attribute allowthirdpartycookies, indicates whether cookies can be delivered in cross-domain mode.
// If you need login Google Account or Other Account, Please set TRUE.
allowThirdPartyCookies: true,
//Attribute supportzoom, indicates whether the H5 page can be zoomed with gestures.
supportZoom:true,
wideViewport:true,
overViewModeLoad:true,
ua:"default",
// Here the whitelist settings, when the loading page has multiple addresses, such as the successful loading of the login address and the inconsistent entry address, it needs to set the whitelist to do so.
list: ["new RegExp('https?.*')"]
},
onInit() {
console.info('onInit: ');
},
onPageStart(e) {
console.info('pagestart: ' + e.url)
},
// Each page switch triggers
onPageFinish(e) {
console.info('pagefinish: ' + e.url, e.canBack, e.canForward);
},
onTitleReceive(e) {
this.title = e.title;
},
onError(e) {
console.info('pageError : ' + e.errorMsg)
},
onMessage(e) {
console.info('onmessage e = ' + e.message + ", url = " + e.url);
},
onShow: function () {
console.info(" onshow");
},
onHide: function () {
console.info(" onHide");
},
onBackPress() {
console.log('onBackPress')
this.$element('web').canBack({
callback: function (e) {
if (e) {
console.log('web back')
this.$element('web').back()
} else {
console.log('router back')
router.back()
}
}.bind(this)
})
return true
},
}
</script>
3) Put your app icon under Common folder. E.g. developer.png
4) Open manifest.json file and paste follwing script and change icon name with the file that you uploaded under Common folder.
Code:
{
"package": "com.testapp.huwei",
"name": "TestApp",
"versionName": "1.0.0",
"versionCode": 1,
"icon": "/Common/developer.png",
"minPlatformVersion": 1060,
"features": [
{
"name": "system.configuration"
},
{
"name": "system.calendar"
},
{
"name": "system.prompt"
},
{
"name": "system.router"
}
],
"permissions": [
{
"origin": "*"
}
],
"config": {},
"router": {
"entry": "Hello",
"pages": {
"Hello": {
"component": "hello"
}
}
},
"display": {
"titleBar":false
}
}
4) Create .rpk package by using Build > Run Release direction.
5) Accept IDE to create a signature file for your app.
6) com.testapp.huawei_release_1.0.0.rpk package has been generated and ready for test.
For more details...
Links
How can we convert an H5 app into a Quick App with Online Conversion:
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201240455899740095&fid=0101188387844930001
More information like this, you can visit HUAWEI Developer Forum
This article covers to draw polylines for different directions types like, Driving, Bicycling and Walking. To get directions response, use OkHttpClient, Volley and Retrofit libraries.
In this article, used Retrofit library to get the response. Check the below code
Code:
private void callDirectionsApi(final String directionType) {
if (!NetworkUtil.isNetworkConnected(this)) {
showNetworkDialog();
return;
}
Origin origin = new Origin();
origin.setLat(13.242430); // Current Location Latitude
origin.setLng(79.277502); // Current Location Longitude
Destination destination = new Destination();
destination.setLat(destinationLocation.getLat());
destination.setLng(destinationLocation.getLng());
DirectionsRequest request = new DirectionsRequest();
request.setOrigin(origin);
request.setDestination(destination);
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<DirectionsResponse> call = apiInterface.getDirections(directionType, request);
call.enqueue(new Callback<DirectionsResponse>() {
@Override
public void onResponse(@NotNull Call<DirectionsResponse> call, @NotNull Response<DirectionsResponse> response) {
if (response.isSuccessful()) {
startEndMarkerList = new ArrayList<>();
DirectionsResponse directionsResponse = response.body();
assert directionsResponse != null;
Log.e(TAG + " Response", directionsResponse.toString());
List<RoutesItem> routesItemList = directionsResponse.getRoutes();
if (routesItemList.size() > 0) {
List<StepsItem> steps = routesItemList.get(0).getPaths().get(0).getSteps();
lineLatLngList = new ArrayList<>();
for (StepsItem stepItem : steps) {
List<PolylineItem> polylineItems = stepItem.getPolyline();
for (PolylineItem polylineItem : polylineItems) {
LatLng latLng = new LatLng(polylineItem.getLat(), polylineItem.getLng());
lineLatLngList.add(latLng);
}
}
Iterable<LatLng> latLngIterable = lineLatLngList;
PolylineOptions polyOptions = new PolylineOptions();
if (directionType == "bicycling") {
polyOptions .width(3);
} else if (directionType == "driving") {
polyOptions .width(5);
} else {
List<PatternItem> pattern = Arrays.asList(new Dot(), new Gap(70));
polyOptions .pattern(pattern);
polyOptions .width(7);
}
polyOptions .color(Color.RED);
polyOptions .jointType(ROUND);
directionsPolyline= huaweiMap.addPolyline(polyOptions );
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : latLngIterable) {
builder.include(latLng);
}
LatLngBounds bounds = builder.build();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 50);
huaweiMap.animateCamera(cameraUpdate);
}
addPolylineCap(lineLatLngList.get(0), R.drawable.grey_circle);
addPolylineCap(lineLatLngList.get(lineLatLngList.size() - 1), R.drawable.white_circle);
addMarkerToMap(destinationLocation, false, destinationName);
animatePolyLine();
}
}
@Override
public void onFailure
(@NotNull Call<DirectionsResponse> call, @NotNull Throwable t) {
Log.e(TAG + " Response Error", Objects.requireNonNull(t.getMessage()));
}
});
}
Dotted and Dashed Polyline:
To draw Dotted and Dashed polyline, following are three classes:
1. Dot
2. Dash
3. Gap
Here based upon directionType changed the width of polyline and for walking path added pattern with new Dot() and new Gap(70) classes.
If we use new Dash() instead of new Dot() we will get dashed polyline.
Code:
if (directionType == "bicycling") {
polyOptions .width(3);
} else if (directionType == "driving") {
polyOptions .width(6);
} else {
List<PatternItem> pattern = Arrays.asList(new Dot(), new Gap(70));
polyOptions .pattern(pattern);
polyOptions .width(10);
}
Polyline Caps:
To add start and end caps for polyline, check the below code.
Code:
addPolylineCap(lineLatLngList.get(0), R.drawable.grey_circle);
addPolylineCap(lineLatLngList.get(lineLatLngList.size() - 1), R.drawable.white_circle);
Instead of adding markers like this, Use default classes for adding caps to polyline, as follows.
1. RoundCap
2. Square Cap
To add this caps to polyline. Check the below code.
Code:
polyOptions.startCap(new RoundCap());
polyOptions.endCap(new CustomCap(getEndCapIcon(Color.BLACK), 100));
Here we can set new RoundCap() and new SquareCap() and also we can give custom cap. Check the below code for adding custom cap.
Code:
public BitmapDescriptor getEndCapIcon(int color) {
// mipmap icon - white arrow, pointing up, with point at center of image
// you will want to create: mdpi=24x24, hdpi=36x36, xhdpi=48x48, xxhdpi=72x72, xxxhdpi=96x96
Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.arrow);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
android.graphics.Bitmap bitmap = android.graphics.Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
Code:
addMarkerToMap(destinationLocation, false, destinationName);
To add custom marker to map. Check my previous article.
Article Link: To customize Maps with Custom Marker and Custom Info Window - Maps Kit
To Animate Polyline like Uber and Swiggy
To animate polylines, Use ValueAnimator to achieve easily. Check the below code.
Code:
private void animatePolyLine() {
ValueAnimator animator = ValueAnimator.ofInt(0, 100);
animator.setDuration(2000);
animator.setInterpolator(new LinearInterpolator());
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
List<LatLng> latLngList = directionsPolyline.getPoints();
int initialPointSize = latLngList.size();
int animatedValue = (int) animator.getAnimatedValue();
int newPoints = (animatedValue * lineLatLngList.size()) / 100;
if (initialPointSize < newPoints) {
latLngList.addAll(lineLatLngList.subList(initialPointSize, newPoints));
directionsPolyline.setPoints(latLngList);
}
}
});
animator.addListener(polyLineAnimationListener);
animator.start();
}
Using AnimatorListener, we can do much more based upon our requirements. Check the below code.
Code:
Animator.AnimatorListener polyLineAnimationListener = new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
if (selectedMarker != null) {
selectedMarker.showInfoWindow();
}
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
};
Find the output in below image
{
"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"
}
Conclusion :
In this articles covers some of the functionalities of Directions. There are lot of concepts are there just try it
Reference links
Driving Direction API:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-References-V5/directions-driving-0000001050161496-V5
Walking Directions API:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-References-V5/directions-walking-0000001050161494-V5
BiCycling Directions API:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-References-V5/directions-bicycling-0000001050163449-V5
will it support available shortest path from origin to destination?
Symptom:
After an image drawn by the canvas component is saved to the album, the image cannot be displayed in the album. Only a black background image is displayed.
The image with the green background in the following figure is drawn by the canvas component.
{
"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"
}
After the image is saved to the album, the display result is as shown in the following figure.
Analysis:
Huawei Quick App Loader creates a ctx object each time it calls the getContext method. Therefore, different ctx objects are returned, and some of these objects are empty. An empty ctx object may be obtained in a random selection. As a result, the saved image may have no content. The code where the exception occurs is as follows:
Code for using canvas to draw an image:
JavaScript:
pic() {
var test = this.$element("canvas");
var ctx = test.getContext("2d");
var img = new Image();
img.src = "http://www.huawei.com/Assets/CBG/img/logo.png";
img.onload = function () {
console.log("Image loaded successfully.");
ctx.drawImage(img, 10, 10, 300, 300, );
}
img.onerror = function () {
console.log("Failed to load the image.");
}
},
Code for saving the image:
JavaScript:
save() {
var test = this.$element("canvas");
test.toTempFilePath({
fileType: "jpg",
quality: 1.0,
success: (data) => {
console.log(`Canvas toTempFilePath success ${data.uri}`)
console.log(`Canvas toTempFilePath success ${data.tempFilePath}`)
media.saveToPhotosAlbum({
uri: data.uri,
success: function (ret) {
console.log("save success: ");
},
fail: function (data, code) {
console.log("handling fail, code=" + code);
}
})
},
fail: (data) => {
console.log('Canvas toTempFilePath data =' + data);
},
complete: () => {
console.log('Canvas toTempFilePath complete.');
}
})
}
Solution:
Define ctx as a global variable and check whether it is empty. Set an initial value for an empty ctx.
The optimized code is as follows:
JavaScript:
var ctx; // Define a global variable.
pic() {
if (!ctx) { // Check whether a ctx object is empty. If it is empty, set its value to 2d.
var test = this.$element("canvas");
var tt = test.getContext("2d");
ctx = tt;
}
var img = new Image();
img.src = "http://www.huawei.com/Assets/CBG/img/logo.png";
img.onload = function () {
console.log("Image loaded successfully.");
ctx.drawImage(img, 10, 10, 300, 300, );
}
img.onerror = function () {
console.log("Failed to load the image.");
}
}
For more details, please check:
Quick app materials:
https://developer.huawei.com/consumer/en/doc/development/quickApp-Guides/quickapp-whitepaper
canvas component:
https://developer.huawei.com/consum...quickApp-References/quickapp-component-canvas
Intro to the canvas API:
https://developer.huawei.com/consumer/en/doc/development/quickApp-References/quickapp-api-canvas
Background
I needed to develop a function for dynamically loading HTML5 websites that matched the system language. The website internationalization in my project was implemented by dynamically loading URLs. For example, if the system language of a mobile phone is Japanese, the URLs of web pages in Japanese are loaded. For simplified Chinese, those in simplified Chinese are loaded, and for English, those in English are loaded, and so on. Here, I have listed the steps for your reference.
{
"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"
}
Solution
Step 1: Bind a variable.
Bind a variable to the src attribute of the web component, to ensure that the attribute will not have a fixed value. In the following code, loadUrl in {{}} is a bound variable. It is defined under script in the UX file. You can skip this step if your project was created using the HTML5 template in Huawei Quick App IDE, downloaded from https://developer.huawei.com/consumer/en/doc/development/quickApp-Guides/quickapp-installtool, because the variable will be bound by the template code.
JavaScript:
<!-- template -->
<web src="{{loadUrl}}"
</web>
<!-- script -->
export default {
data: {
loadUrl: "https://transit.navitime.com/en",
},
Step 2: Initialize the variable.
Use the onInit() method in the quick app’s lifecycle to call the device API to obtain the system language and load the HTML5 page in the obtained language.
JavaScript:
onInit: function () {
const device = require("@system.device")
const res = device.getInfoSync();
let local = res.language; //system language
let region = res.region; //system region
console.info('onInit :localole= ' + local + ", region=" + region);
if (local === 'zh') {
if (region === "CN") {
this.loadUrl = "https://transit.navitime.com/zh-cn/";
} else if (region === "TW") {
this.loadUrl = "https://transit.navitime.com/zh-tw/";
}
} else if (local === 'ja') {
this.loadUrl = "https://transit.navitime.com/ja/?from=huawei.quickapp";
} else {
// For other languages, the HTML5 page in the default language is used.
this.loadUrl = "https://transit.navitime.com/en";
}
},
Step 3: Add a listener for system language switch.
Perform this step if you want the language on the HTML5 page to change accordingly, as the user changes the system language when the HTML5 quick app is running. You can skip this step if you don’t need to implement this function. The user can simply exit the app and re-enter it.
The code for adding a listener to listen to the system language switch is as follows:
JavaScript:
onConfigurationChanged(object) {
console.log("onConfigurationChanged object=" + JSON.stringify(object));
if (object.type === "locale") {
const configuration=require("@system.configuration")
var localeObject = configuration.getLocale();
let local= localeObject.language;
let region= localeObject.countryOrRegion;
console.info(onConfigurationChanged(object :localole= ' + local + ", region=" + region);
if (local === 'zh') {
if (region === "CN") {
this.loadUrl = "https://transit.navitime.com/zh-cn/";
} else if (region === "TW") {
this.loadUrl = "https://transit.navitime.com/zh-tw/";
}
} else if (local === 'ja') {
this.loadUrl = "https://transit.navitime.com/ja/?from=huawei.quickapp";
} else {
// For other languages, the HTML5 page in the default language is used.
this.loadUrl = "https://transit.navitime.com/en";
}
}
},
Summary
I hope you’ll find this post helpful, when planning the global release of your HTML5 quick app. Feel free to leave a question or comment below, to share your own experiences.
It's an easy and useful code.
Rebis said:
It's an easy and useful code.
Click to expand...
Click to collapse
Thanks to your liking.