Hongmeng application development FAQ

Posted by itsmeArry on Fri, 24 Dec 2021 23:22:50 +0100

1, Hongmeng application development environment preparation:

1. Download and install the development software

reference resources

2. Configure the development environment reference resources

Supplement:

DevEco Studio provides the SDK Manager to manage the SDK and tool chain uniformly. When downloading SDK packages of various programming languages, the SDK Manager will automatically download the tool chain that the SDK package depends on.

2.1 corresponding dependent development sdk:

  • Corresponding Java language SDK package of Hongmeng
  • Native language SCK package
  • There are also SDK packages for JS language.

2.2 other corresponding tool chains

  • Toolchains: SDK tool chain, a necessary tool set for HarmonyOS application development, including a collection of tools such as compilation, packaging, signature and database management.

Tool chain environment configuration, which can be used globally after configuration

mac system: in < bash_ Add the following configuration (. bash_profile file is located in the user directory) to profile >

export HARMONY_HOME=/Users/lingge/Library/Huawei/sdk/toolchains
export PATH=$PATH:$HARMONY_HOME

windows system: add this path directly to path.

There is an hdc tool in the tool chain, which can be used to install the typed hap package, similar to the adb tool in Android sdk

#The command to install the hap package is
hdc app install xxx.hap

2.3 preview tool Preview:

HarmonyOS application previewer can dynamically preview the application effects of Phone, TV, Wearable, LiteWearable and other devices during development, and supports JS and Java application previews.

2, Real machine commissioning preparation

2.1 upgrade Hongmeng system first

Reference documents

2.2 compile build generate HAP

Refer to official documents

2.3 specific commissioning:

Refer to official documents

3, Development FAQ

1. Hongmeng WebView uses:

webview:https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ui-java-component-webview-0000001092715158

If the WebView container needs to allow js execution, the following settings are required:

webView.getWebConfig().setJavaScriptPermit(true); 

If the WebView container is used, the corresponding business calls window Storage API, the following settings are required:

webView.getWebConfig().setWebStoragePermit(true); 

How webView determines whether the current container stack can go back and forward:

Navigator navigator = webView.getNavigator();
if (navigator.canGoBack()) {
 		navigator.goBack();
	}
if (navigator.canGoForward()) {
	    navigator.goForward();
	}

How does WebView listen to browsing events, including H5 page request location processing

webView.setBrowserAgent(new BrowserAgent(this) {
    @Override
    public void onTitleUpdated(WebView webview, String title) {
        super.onTitleUpdated(webview, title);
        // Custom processing when Title Changes
    }

    @Override
    public void onProgressUpdated(WebView webview, int newProgress) {
        super.onProgressUpdated(webview, newProgress);
        // Custom processing when loading progress change
    }
     @Override
    public void onLocationApiAccessRequest​(String origin, LocationAccessController.Response response){
    	//H5 page request positioning custom processing
    }
    
});

2. Use of Hongmeng permission

Permission list: Reference documents

Permission statement and application: Reference documents

The location permission needs to be dynamically applied, and the Context needs to be Ability, otherwise an error will be thrown, resulting in the termination of the process

canRequestPermission can't requestPermission,ability is not instance of AbilityShellActivity

3. How to determine whether Android APP is installed on Hongmeng system:

/**
 * Determine whether the package is installed
 *
 * @param context
 * @param pkgName Package name
 * @return  Is it installed
 */
public static boolean checkApkExist(Context context, String pkgName) {
    if (context == null || StringUtils.isEmpty(pkgName)) {
        return false;
    }
    try {
        IBundleManager bundleManager = context.getBundleManager();
        return bundleManager.isApplicationEnabled(pkgName);
    } catch (IllegalArgumentException exception) {
        HiLog.error(TAG, "MainAbility::exception " + exception.getMessage());
    } catch (Exception ex) {
        HiLog.error(TAG, "MainAbility::exception " + ex.getMessage());
    }
    return false;
}

4. How to determine whether a Hongmeng APP is installed:

Reference forum posts

IBundleManager.getBundleInfo(String  bundleName,int userId) Interface to know if a is installed app

To use this method, you need to request from the system: ohos permission. GET_ BUNDLE_ INFO_ Privileged or ohos permission. GET_ BUNDLE_ Info permissions. ohos.permission.GET_BUNDLE_INFO_ The privileged permission is at the signature|privileged level, ohos permission. GET_ BUNDLE_ Info permission is normal level.

uesrId defaults to 0, indicating the primary user

5. How to jump to the application market

/*Jump to APP market APP installation page*/
private void startAppMarketDetailPage(Ability context, String appPkg) {
    Uri uri = Uri.parse("market://details?id=" + appPkg);
    Intent intentMarket = new Intent();
    intentMarket.setAction("android.intent.action.VIEW");
    intentMarket.setUri(uri);
    intentMarket.setBundle("com.huawei.appmarket");
    intentMarket.addFlags(Intent.FLAG_ABILITY_NEW_MISSION);
    context.startAbility(intentMarket);
}

6. How does Hongmeng Ability hide the default TitleBar

//In config The child nodes corresponding to the Ability configuration in JSON are added as follows: metaData configuration
"metaData": {
  "customizeData": [
    {
      "name": "hwc-theme",
      "value": "androidhwext:style/Theme.Emui.Light.NoTitleBar"
    }
  ]
}

7. Network request failed

There are very few error logs in Hongmeng system.

1. First confirm that the corresponding network request permission is in config JSON.
2. Then check the error information that may be thrown by the whole request link. Including request result parse failure,
3. Confirm that the UI view is not directly updated in the sub thread of the network request.
4. https link must be used

8.Hilog logs are not printed

https://developer.huawei.com/consumer/cn/forum/topic/0201618435909840010?fid=0101587865002800104

There are two reasons why the HiLog log does not print when debugging code:

1. The Log window does not display anything

Problem cause: the log system is occupied by other applications or the local 5037 log service is not opened.
Example: two ides are opened. One of them may not be displayed.

terms of settlement:

View the occupation of 5037 port:

Then delete all occupied tasks:

2. The system has a print log, but its own Hilog log does not, as shown in the figure below.

Cause of problem:

The HiLog service is not turned on.

terms of settlement:

Enter the dialing interface, enter: ##2846579##, enter the background setting - > aplog setting, select open, and then restart the devico ide tool to trigger the reconnection between Hdc and HiLog service.

9. How does WebView open a new link on the current page

https://developer.huawei.com/consumer/cn/forum/topic/0201540619529700034?fid=0101303901040230869

The core code is as follows:

    WebView webView = new WebView(getContext());

    webView.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);

    webView.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);

    //Custom URL loading method

    webView.setWebAgent(new ExampleWebAgent());

    DirectionalLayout component = (DirectionalLayout) findComponentById(ResourceTable.Id_webview);

    component.addComponent(webView);

    webView.load(EXAMPLE_URL);





private class ExampleWebAgent extends WebAgent {

    @Override

    public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {

        Uri uri = request.getRequestUrl();

        if (EXAMPLE_URL.equals(uri.getDecodedHost())) {
        	//Custom processing
            return false;
        }

        // Default processing
        return super.isNeedLoadUrl(webView, request);

    }

}

10. How does Hongmeng set the theme

//In config The child nodes corresponding to the Ability configuration in JSON are added as follows: metaData configuration, in which the value value corresponds to the theme style, but it is a black box for developers at present.

"metaData": {
  "customizeData": [
    {
      "name": "hwc-theme",
      "value": "androidhwext:style/Theme.Emui.Light.NoTitleBar"
    }
  ]
}

Currently known hidden default TitleBar: Android wext: style / theme Emui. Light. NoTitleBar
Transparent background theme: Android wext: style / theme Emui. Translucent. NoTitleBar

11 How does Hongmeng set the background of the current Ability to be transparent

1. Add the following topic configuration under the corresponding Ability node

//Add the following transparent background theme under the corresponding Ability node
"metaData": {
	  "customizeData": [
	    {
	      "name": "hwc-theme",
	      "value": "androidhwext:style/Theme.Emui.Translucent.NoTitleBar"
	    }
	  ]
	}

2. Add the following code to onStart in the corresponding Ability class

   WindowManager.getInstance().getTopWindow().ifPresent(window -> {
        window.setTransparent(true);//Allow transparency
        window.addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);//Set status bar transparency
  window.clearFlags(WindowManager.LayoutConfig.MARK_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    });

12 Shap resource declaration gradient background

The custom shap resources in Hongmeng are also in XML format and can be declared in the resource/base/graphic Directory:
At present, the gradient background declared in the resource shap can only be up and down, and there is no exposed method declaration angle.
The left and right can be set through the following Declaration:

 <?xml version="1.0" encoding="utf-8"?>
	<shape
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">

    <corners ohos:radius="3vp"/>
    <solid
        ohos:colors="#FFFFFF,#000000"/>
</shape>

If you need an angle, you can use ShapeElement in the code. ShapeElement
Reference implementation:

//Code to achieve a certain angle gradient, shapeelement Orientation has several fixed values to choose from
ShapeElement btnBgElement = new ShapeElement();
btnBgElement.setShape(ShapeElement.RECTANGLE);
RgbColor[] rgbColors = new RgbColor[]{RgbColor.fromArgbInt(0xFFFB54AA), RgbColor.fromArgbInt(0xFFFD5773)};
btnBgElement.setRgbColors(rgbColors);
btnBgElement.setCornerRadius(DisplayUtils.vp2px(40F));
btnBgElement.setGradientOrientation(ShapeElement.Orientation.LEFT_TO_RIGHT);
downloadBtn.setBackground(btnBgElement);

13 How to set rich text

Hongmeng java module does not support rich text temporarily, which can be supported in js code

14 how to convert the virtual unit vp of Hongmeng into px and how to obtain the screen width and height

Hongmeng provides system tools:
AttrHelper

Reference implementation class:

/**
 * Device screen properties
 */
public class DisplayUtils {
    public static int getScreenWidth() {
        DeviceCapability deviceCapability = getDeviceCapability();
        return deviceCapability.width;
    }

    public static int getScreenHeight() {
        DeviceCapability deviceCapability = getDeviceCapability();
        return deviceCapability.height;
    }

    public static DeviceCapability getDeviceCapability() {
        DeviceCapability deviceCapability = DemoAPPInfo.getInstance().getApplicationContext().getResourceManager().getDeviceCapability();
        return deviceCapability;
    }

    public static int vp2px(float vp) {
        return AttrHelper.vp2px(vp, DemoAPPInfo.getInstance().getApplicationContext());
    }
}

15 Hongmeng's judgment and monitoring of "dark mode"

The onConfigurationUpdated method provided by the current Application and Ability cannot be called back.
However, in the card service, dark mode switching will start the update of the card. At this time, you can obtain the current system mode through the following methods:

//Gets whether the current system is in dark mode
boolean darkMode = context.getResourceManager().getConfiguration().getSystemColorMode() == Configuration.DARK_MODE;

16 how to command the installation of Hongmeng hap package

#The command to install the hap package is
hdc app install xxx.hap

The hdc command is located in the toolchains directory of Hongmeng sdk. mac needs to export the path to path, and windows needs to configure the environment variable to path

17 how to switch from Hongmeng sub thread to UI thread

context.getUITaskDispatcher().asyncDispatch(new Runnable(){...})

Hongmeng card development FAQ:

1.js card image loading, will it support direct remote connection later?

Not supported at the moment. At present, you can only bind the picture data to the card in byte [] after downloading. Caching needs to be done by yourself

2. The JS card does not support a single expression after the if keyword, for example: a==1,! A. the variable value must be a direct bool value

3.js card data does not support object nesting. After nesting, the data cannot be retrieved

4. The id of UI XML root element in ability cannot be found

5. After the card runs, it will start an empty page first. How to remove this

The card is in config The declaration in JSON is hung on an Ability, which is the default page pulled up by the service after the user finds the service in the service center. Specific undertaking contents are required and cannot be blank.

6. When using the context of Application to obtain the location, the error is thrown directly and the execution is interrupted

You can try using Ability.

8. Confusion,

Similar to Android reference resources

9. The EntryCard directory in the card engineering structure cannot be deleted

After deletion, an error will be reported when compiling. Even if the debug package does not compile, an error will be reported when compiling and packaging the release package. The error information is irrelevant.
For the specific configuration of this directory, refer to Official documents

10. How are the js directory and java directory linked in the js card project

After the js card is created successfully, click config A js module will be generated in the module of JSON, which is used for the js related resources of the corresponding card. The configuration example is as follows:

"js": [
  {
    "name": "card", //Card name and corresponding directory name
    "pages": [
      "pages/index/index"//Page UI template file
    ],
    "window": {
      "designWidth": 720,
      "autoDesignWidth": true
    },
    "type": "form" // Type declaration
  }
]

config. The configuration details of the forms module in the ability sub node of the "hang on this card" JSON file are as follows. See Table 1 for details of each attribute.

"forms": [
  {
    "name": "Form_Js",
    "description": "form_description",
    "type": "JS",
    "jsComponentName": "card",//Associated to the corresponding js declaration file
    "formConfigAbility": "ability://com.huawei.demo.SecondFormAbility",
    "colorMode": "auto", //Follow system theme color mode
    "isDefault": true,// Is it the card displayed by default
    "updateEnabled": true,
    "scheduledUpdateTime": "10:30",
    "updateDuration": 1,
    "defaultDimension": "2*2",
    "supportDimensions": [
      "2*2",
      "2*4",
      "4*4"
    ],
    "metaData": {
      "customizeData": [
        {
          "name": "originWidgetName",
          "value": "com.huawei.weather.testWidget"
        }
      ]
    }
  }
]

Topics: Harmony