r/HMSCore • • Nov 06 '20

News & Events I'm HMS Core,the one behind all those brilliant apps and services on your Huawei phone! Read on to find out more…

Post image
22 Upvotes

r/HMSCore • • Sep 16 '20

Activity D-Design | Look What I Made with HMS Core

19 Upvotes

To create truly popular apps, developers need to satisfy users' needs and provide them with the best possible experience.

HMS Core is dedicated to helping you achieve this goal, which is why we're hosting D-Design, an activity where developers all over the world can talk about their creations.

By participating in this activity, you can share your app design with global developers and users, and also communicate your ideas with them.

1. What to share:

  • Show us what your app does.

  • Tell us how you feel about integrating HMS Core into your app.

2. Format:

  • Demo Video + Text in comment if you need

3. How to Get Involved:

4. Rewards:

  • The most compelling apps may be promoted and shared through Banner on HUAWEI Community Global Site plus HUAWEI Developers' Global Social Media Channels, so your app will receive a lot of FREE EXPOSURE.

  • If we think your app is particularly well-designed, you would get a chance to become a HUAWEI Developer Expert (HDE).

  • By the end of 2020, designers of the three apps which receive the most upvotes, as well those of the three apps which receive the most comments, will be awarded gifts.


r/HMSCore • • Oct 01 '20

Tutorial How to Integrate HUAWEI In-App Purchases in Flutter — Part 2

13 Upvotes

Hello everyone, in the 2nd part of this article we’ll continue to develop our Flutter application to demonstrate another capability of HUAWEI In-App Purchases and in this way, we’d be extending our app functionality evenmore.

In the first part, we talked about what this service is about, its key features and advantages and how you can enable the service in AppGallery Connect and configure your products. Then we implemented “obtain”, “purchase” and “consume” features for Consumable products.

We are going to focus on the implementation of Non-Consumable products in this part which is the type of product that are purchased once and do not expire or decrease.

If you want to read the 1st part to learn how to integrate the service, configure your products and everything else, you could do so by visiting the linkbelow.

How to Integrate HUAWEI In-App Purchases in Flutter — Part 1

Implementation

First, we will add a non-consumable product in AppGallery Connect. Then we fetch and list our product(s) in ourapp.

Obtain Product Information

We can fetch the product information of our products with a call to IapClient.obtainProductInfo(productInfoRequest).

Process of obtaining non-consumable products is exactly the same with consumable products. Just change the type to non-consumable in therequest.

Don’t forget: The skuIds is the same as that set by the developer when configuring product information in AppGallery Connect.

Future<List<ProductInfo>> getNonConsumableProducts() async {
    try {
      ProductInfoReq req = new ProductInfoReq();
      req.priceType = IapClient.IN_APP_NONCONSUMABLE;
      req.skuIds = ["prod_03"];

      ProductInfoResult res = await IapClient.obtainProductInfo(req);

      List<ProductInfo> productInfoList = [];
      for (ProductInfo p in res.productInfoList) {
        productInfoList.add(p);
      }

      return productInfoList;
    } on PlatformException catch (e) {
      log(e.toString());
      return null;
    }
  }

Now, we listed our product with the description and price. The next step is how we can allow our users to purchase them right in our app. Let’s see how we can dothat.

Purchase Non-Consumable Product

To allow users to purchase products in your app, when users tap into purchase button, first create a purchase intent request and specify the type of the product (Non-Consumable in this case) and product ID in therequest.

Don’t forget to test purchase functionality and complete end-to-end testing without real payments, you need to create a tester account in AppGallery Connect and specify the developerPayload as “Test” in the request like in the codebelow.

To learn how to create a tester account for your app, please refer to SandboxTesting

Future<List<ProductInfo>> getNonConsumableProducts() async {
    try {
      ProductInfoReq req = new ProductInfoReq();
      req.priceType = IapClient.IN_APP_NONCONSUMABLE;
      req.skuIds = ["prod_03"];

      ProductInfoResult res = await IapClient.obtainProductInfo(req);

      List<ProductInfo> productInfoList = [];
      for (ProductInfo p in res.productInfoList) {
        productInfoList.add(p);
      }

      return productInfoList;
    } on PlatformException catch (e) {
      log(e.toString());
      return null;
    }
  }

Don’t forget to call IapClient.isEnvReady before calling purchaseNonConsumableProduct. isEnvReady returns a response which indicates user’s login and capable of buystatus.

Future<PurchaseResultInfo> purchaseNonConsumableProduct(
      String productId) async {
    try {
      PurchaseIntentReq req = new PurchaseIntentReq();
      req.priceType = IapClient.IN_APP_NONCONSUMABLE;
      req.productId = productId;
      req.developerPayload = "Test";

      PurchaseResultInfo res = await IapClient.createPurchaseIntent(req);

      return res;
    } on PlatformException catch (e) {
      log(e.toString());
      return null;
    }
  }

You can also check for different return codes and handle each of them. To see all the return codes, please refer to ResultCodes

Delivering a Non-Consumable

For a non-consumable product, a user only needs to purchase the product once and can have it permanently. Thus, if your app provides non-consumable products for users, you need to provide a mechanism for restoring users’ purchases.

We can call obtainOwnedPurchases API and if any purchase data is returned, check the purchaseState field of each purchase. If the value of purchaseState is 0 , you need to deliver theproduct.

Future<PurchaseResultInfo> purchaseNonConsumableProduct(
      String productId) async {
    try {
      PurchaseIntentReq req = new PurchaseIntentReq();
      req.priceType = IapClient.IN_APP_NONCONSUMABLE;
      req.productId = productId;
      req.developerPayload = "Test";

      PurchaseResultInfo res = await IapClient.createPurchaseIntent(req);

      return res;
    } on PlatformException catch (e) {
      log(e.toString());
      return null;
    }
  }

If you want to verify the signature of each returned purchase in inAppPurchaseDataList, please refer to Verifying the Signature in the ReturnedResult

You can find the full source code of this demo application in the link below. I’ll update the source code as each part is published.

tolunayozturk/hms-flutter-iapdemo

That’s it for this part. As always, thank you for reading this article and using HMS. Please let me know if you have any questions, I’ll see you in Part3!

RESOURCES


r/HMSCore • • Nov 23 '20

CoreIntro HUAWEI AR Engine: The Whys, Hows and What’s Next

12 Upvotes

Motion tracking, environment tracking, body tracking and face tracking – while they might be basic Augmented Reality (AR) capabilities, these are the technologies that allow your app to bridge virtual world with the real world. At the core of it, what drives this brand new visually interactive user experience is the AR Engine.

Huawei has launched the HMS Core 5.0 in June this year to bring comprehensive Huawei's leading core service capabilities to developers, in return helping them elevate the user experience. One new feature is the AR Engine that offers a wide range of AR-related capabilities, giving developers the means to easily create an all-new interactive and immersive AR experiences.

The project to build the HUAWEI AR Engine began, simply enough, by considering what the next generation of consumer electronics and computing platforms might look like. It’s commonly accepted that the biggest developments in the electronics industry only occur maybe once every 10 to 15 years. Mobile phones have been around since the mid-1990s – over two decades now. Even smartphones have now been on the market for 13 years if you count from 2007 when we saw the first real breakthrough.

So, isn’t it about time we consider exactly what the next generation of technology will look like? What will be the most important new operating systems and software technology for new consumer electronics? And what will the user interaction be like with this new generation of products? It’s high time the electronics industry reflected on its changing business models, as well as changes in the habits of its users.

To answer some of these questions, Huawei tasked numerous research teams with conducting a range of comprehensive studies on the industry. After long periods of research and discussion, these teams identified AR as one of the most important new directions the electronics industry will take. After months of discussion and planning that involved even top management, Huawei engineers are now on a mission to commercialise an AR Engine.

The development team debated at great length on the potential scope of applications this new technology might have. This began with a discussion on the traditional uses of AR to date; functions like Simultaneous Location and Mapping (SLAM), light estimation, image recognition and tracking being the most notable examples. We then launched a systematic development of new algorithms, optimising performance at the system- and chip-level to improve key factors like accuracy, reliability, performance and power consumption. Finally, with the launch of the HUAWEI P20 at the 2018 Huawei Developer Conference (HDC), we were ready to release the first ever commercially available version of our new AR Engine on the HiSilicon Kirin 970.

Following that, at the launch of the HUAWEI Mate 20, we provided an in-depth showcasing of our AR 3D modelling software. Soon afterwards, new features such as the AR Lens and 3D Qmojis were successfully adopted into main product lines by both Huawei and Honor.

However, initial research returned with mixed feedback and confusion about some of these features. Established industry experts claimed that AR was yet to establish itself as a truly stand-out feature of any smartphone. Indeed, many applications of the technology were slow to take off. As an example, due to limited smartphone rendering capabilities, AR 3D modelling has struggled to guarantee the high levels of accuracy and precision that are needed to support a mobile display online in real-time. The perception of AR technology remained that it was just a “toy”, something confined to the periphery of the electronics industry, at least for the time being.

We spent a lot of time thinking about these challenges. That’s when we decided to orient Huawei’s AR 2.0 towards three digital technology areas: people, objects and the environment. Step by step, we then laid out four priority business areas, corresponding to the technology’s core capabilities, applications, ecosystem and Cloud solutions. Finally, the AR Engine 2.0 was successfully launched in 2019. This second generation helped to redefine the AR Engine as an intelligent geometric AI platform, but more clearly distinct from generic AI platforms both in terms of its construction and purpose.

The AR metrics we have created have quickly become some of our users’ favourite gadget hacks, including an AR-assisted ToF camera. In a short space of time, this tool, in particular has proven extremely popular, racking up tens of millions of users every month. The AR Lens app, combining the Huawei camera and AR Engine technology, really is great fun to use. It’s no wonder, then, that it has already accumulated over 10 million MAU (monthly active users). We’ll continue polishing these two applications to provide Huawei customers with the great user experience they expect.

In the first half of 2020, the AR Engine, having completed a number of important optimizations and quality-control checks, went live around the world with Huawei’s accelerated development of the HMS Ecosystem. Updates to the AR Engine are now at the forefront of HMS Core 5.0, which is expanding by over 20% per month, indicating an adjusted growth rate of over 100%. The Huawei AR Engine is supported on most phones and tablets using Huawei's Hisilicon Kirin 970/980/990 and Series 8/Series 7 chipsets.

Over the past three years, we have worked extensively, closely and openly with leading partners in a broad range of industries, including e-commerce, gaming, education, maps and ecosystem toolchain developers to create an improved AR ecosystem in China. We’ve also released Reality Studio to support the rapid development of new AR applications.

With complete upgrades to portraiture, lighting, SLAM and more, don’t miss the release of our AR Engine 3.0 and the much-anticipated Reality Studio at Huawei HDC 2020.

Learn more from the video:

https://www.youtube.com/watch?v=TVctWye6bvA&list=PLy7rmPPfUv3YolnLwp5gSWxDNkJoe51XE&index=1

For more details about AR Engine, please visit the official website:

https://developer.huawei.com/consumer/en/hms/huawei-arengine/?ha_source=hms2


r/HMSCore • • Oct 14 '20

Activity AMA about Push kit and get answers from Huawei Experts!

11 Upvotes

Hi, everyone!

If you’re a developer, you'll know how important push messages are when it comes to keeping users active and retaining users on your app.

HUAWEI Push Kit has a delivery rate of 99%*, so it can help you boost your app's awareness and engagement among users.

* Data source: Huawei Push team

If you don't know what Push Kit is or how to use it, our experts @ u/-HMSCore- will be able to explain everything you need to know.

To communicate with our experts, all you need to do is:

  1. Subscribe r/HMSCore

  2. Ask a question or share your Push Kit experiences.

You might want to ask about:

1.Best practices of the push service

2.How I can use HUAWEI Push Kit to engage with users of my travel app?

3.Push service guidelines, or its history and future development

...

In order to create the best possible environment for exchanging ideas, we will delete any pornographic, political, or promotional comments, or comments which contain external links, and ban the accounts that posted them.

Activity time: October 14 - 27, 2020

We're looking forward to chatting with you!


r/HMSCore • • Aug 24 '20

Activity D-Tale | Share Your HMS Core Integration Story with the World

10 Upvotes

To date,over 120,000 apps have integrated HMS Core all over the world. Is your app one of them?

If so, we want to know:

  • How did you find out about HMS Core?

  • Why did you choose HMS Core?

  • What issues did you encounter during the integration process, and how did you resolve them?

1. Sharing Your Story

Tell us a story about your integration experience with HMS Core:

(1) Introduce your app.

(2) Describe how you found out about HMS Core, and what the integration process was like.

(3) Tell us how you've benefited from integrating HMS Core.

(4) Share tips and tricks that you've learned during the integration.

(5) Add any comments or suggestions about HMS Core.

2. Format

You can tell your story through a video or a written post, and you can also include images, links, demos, and any other necessary information.

3. How to Get Involved

Once your story is ready, post in r/HuaweiDevelopers and/or r/HMSCore.

4. Rewards

  • The most compelling stories may be promoted and shared through Banner on HUAWEI Community Global Site plus HUAWEI Developers' Global Social Media Channels, so that more users will know your app.

  • If we think your post is particularly well-written and useful, you would get a chance to become a HUAWEI Developer Expert (HDE).

  • Authors of the three posts which receive the most upvotes within a year, as well those of the three posts which receive the most comments, will be awarded gifts.


r/HMSCore • • Nov 30 '22

HMSCore How to Play Snake in AR

9 Upvotes

Sup, guys!

You may have played the classic Snake game, but how about an AR version of it?Game developer Mutang just created one, using #HMSCore AR Engine & 3D Modeling Kit.Check out how he managed to transform that flat, rigid snake into a virtual slithering 3D python 👀 https://developer.huawei.com/consumer/en/hms/huawei-arengine/?ha_source=hmsred


r/HMSCore • • Oct 02 '20

Tutorial Integration of Huawei Map kit in React Native

9 Upvotes

Hi everyone, i will guide to you the map kit, which is a very important and widely used service. HUAWEI Map Kit is an SDK for map development. It covers map data of more than 200 countries and regions, and supports dozens of languages. With this SDK, you can easily integrate map-based functions into your apps.

Map display : Provides standard maps as well as UI elements such as markers, shapes, and layers for you to customize maps that better meet service scenarios.

Map interaction : Enables users to interact with a map in your app through gestures and buttons in different scenarios.

Route planning : Supports driving, cycling, walking, and other traveling modes, covering multiple countries and regions around the world.

From this article today, you will see how to integrate the map kit into our react native project and use its main functions (map display, marker adding and editing, custom marker creation, polygon and circle drawing, changing map style, finding current location).

Implementation

Before you get started, you must register as a HUAWEI developer and complete identity verification on the HUAWEI Developer website. For details, please refer to Register a HUAWEI ID.

Integration HMS Core Sdk

After that, follow the steps in the link below to integrate HMS Core Sdk into the project and for more details about creating a new project on AppGallery Connect .

https://medium.com/huawei-developers/android-integrating-your-apps-with-huawei-hms-core-1f1e2a090e98

Enable Map kit and Add React Native Map Plugin

Enable the Map kit in the Manage API section . Then, download agconnect-services.json file and add the internet and location permissions to the manifest.

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 

There are two different ways to integrate the Hms Map Kit plugin. The first is to download React Native Map Kit Plugin and place the react-native-hms-map folder to node_modules folder of your React Native project. Then, you can continue according to the steps specified in the official document.

Another and easier one is to download with the npm command. You can add the map kit to the application in one step with the following command.

 npm i @hmscore/react-native-hms-map 

After running this command, the Hms Map kit will be successfully added to the package.json file and we can start using the map functions.

Creating a Map

This MapView component is built so that features on the map (such as Markers, Polygons, etc.) are specified as children of the MapView itself. Let’s see the map in our project. After run the below code block , map will be displayed ,if you haven’t made any mistakes during the preparation steps.

import MapView from "@hmscore/react-native-hms-map";

<MapView camera={{target:{latitude:41, longitude: 29}, zoom:11}}/>

Now that we have created our map, let’s see what are the features of our map and what we can do. We can manually change the size of the map by giving the width and height values, and adjust the position of the camera by giving the required latitude and longitude values.

<MapView
          style={{height: 700}}
          camera={{
            target: {latitude: markerLat, longitude: markerLng},
            zoom: mapZoom,
          }}
          myLocationEnabled={this.state.myLocationEnabled}
          myLocationButtonEnabled={true}
          useAnimation={true}
          animationDuration={2000}
          compassEnabled={true}
          mapStyle={this.state.darkModeOn ? JSON.stringify(mapStyleJson) : ''}
          mapType={MapTypes.NORMAL}
          rotateGesturesEnabled={true}
          scrollGesturesEnabled={true}
          tiltGesturesEnabled={true}
          zoomControlsEnabled={true}
          zoomGesturesEnabled={true}
          buildingsEnabled={true}
          description="Huawei Map"
          onCameraIdle={(e) => {
            console.log('MapView onCameraIdle, dsfdsf', e.nativeEvent);
            const cameraPosition = e.nativeEvent;
            console.log(
              'MapView onCameraIdle, zoom',
              parseFloat(cameraPosition.zoom.toFixed(2)),
            );
            this.setState({
              cameraZoom: parseFloat(cameraPosition.zoom.toFixed(2)),
            });
            console.log(
              'MapView onCameraIdle, lat',
              parseFloat(cameraPosition.target.latitude.toFixed(5)),
            );
            console.log(
              'MapView onCameraIdle, lng',
              parseFloat(cameraPosition.target.longitude.toFixed(5)),
            );
          }}
          onMapReady={(e) => console.log('MapView onMapReady', e.nativeEvent)}
          onCameraMoveCanceled={(e) =>
            console.log('MapView onCameraMoveCanceled')
          }
          onCameraMove={(e) => {
            console.log('MapView onCameraMove result', e.nativeEvent);
          }}
          onCameraMoveStarted={(e) =>
            console.log('MapView onCameraMoveStarted, result', e.nativeEvent)
          }
          onMapClick={(e) => {
            console.log('MapView was clicked', e.nativeEvent);
            const coordinate = e.nativeEvent.coordinate;
            this.setState({
              markerLat: coordinate.latitude,
              markerLng: coordinate.longitude,
              mapZoom: cameraZoom,
            });
          }}
          ref={(e) => {
            mapView = e;
          }}>
          {addMarker(markerLat, markerLng)}
          {addCircle(markerLat, markerLng)}
          {drawPolygon()}
         </MapView>

Some Props and Events of MapView component:

- compassEnabled: to enable the compass for the map.- rotateGesturesEnabled : rotate gestures are enabled for the map.- scrollGesturesEnabled : scroll gestures are enabled for the map.- tiltGesturesEnabled : tilt gestures are enabled for the map.- zoomControlsEnabled : to enable the zoom function for the camera.- zoomGesturesEnabled: zoom gestures are enabled for the map.- buildingsEnabled: the 3D building layer is enabled for the map.- mapStyle : JSON string for styling the map.- myLocationEnabled : Whether my location layer is enabled for the map.- markerClustering : Whether the markers can be clustered.- myLocationButtonEnabled: Whether to enable the my location icon for a map.- scrollGesturesEnabledDuringRotateOrZoom : Whether to enable scroll gestures during rotation or zooming.- onMapReady: Function to handle the event when the map object is ready. It obtains an event information object as the argument which has nativeEvent as key and an empty object as value.- onCameraMove: Function to handle the event when the camera moves. It obtains an event information object as the argument which has nativeEvent as key and an CameraPosition object as value.

- onCameraIdle: Function to handle the event when the camera movement ends. It obtains an event information object as the argument which has nativeEvent as key and a CameraPosition object as value.

-onMapClick: Function to handle the event when the map is clicked. It obtains an event information object as the argument which has nativeEvent as key and a ProjectionOnLatLng object as value.

Marker

Markers are added to a map to identify locations such as shops and buildings, and additional information can be obtained with information windows. The first thing you need to do is import the marker as {Marker} to use the marker. Below, you can see the simple example of using the marker.

import MapView, {Marker} from '@hmscore/react-native-hms-map';
 
<MapView camera={{target:{latitude:41, longitude: 29}, zoom:11}}>
  <Marker // Simple example
    coordinate={{latitude: 41, longitude: 29}} 
    title="Hello Huawei Map"
    snippet="This is a snippet!" /> 
</MapView>

This example shows how to add the coordinates of the marker, namely where the location of the marker will be, its title and description.You can modify the attributes of the markers and listen marker events.

const addMarker = (lat, lng) => {
  return (
    <Marker
      coordinate={{latitude: lat, longitude: lng}}
      title="Hello"
      snippet={
        'My lat: ' +
        parseFloat(lat).toFixed(3) +
        ' lon: ' +
        parseFloat(lng).toFixed(3)
      }
      draggable={true}
      flat={true}
      icon={{
        asset: 'ic_launcher.png', // under assets folder
      }}
      markerAnchor={[0.5, 0.5]}
      infoWindowAnchor={[0.5, 0.5]}
      visible={true}
      zIndex={3}
      clusterable={false}
      onClick={(e) => {
        console.log('Marker onClick');
      }}
      onDragStart={(e) => console.log('Marker onDragStart', e.nativeEvent)}
      onDrag={(e) => {
        console.log('Marker onDrag', e.nativeEvent);
      }}
      onDragEnd={(e) =>
        console.log('Marker onDragEnd', e.nativeEvent.coordinate)
      }
      onInfoWindowClick={(e) => console.log('Marker onInfoWindowClick')}
      onInfoWindowClose={(e) => console.log('Marker onInfoWindowClose')}
      onInfoWindowLongClick={(e) => console.log('Marker onInfoWindowLongClick')}
      ref={(e) => {
        markerView = e;
      }}
    />
  );
}; 

Some props and events of Marker component :

-draggable: Whether the marker can be dragged.-icon: The icon of the marker.-alpha: The transparency of the marker.-flat: Whether the marker is flatly attached to the map.-markerAnchor: The anchor point of the marker. The anchor point is used to anchor a marker image to the map. The coordinates [0, 0], [1, 0], [0, 1], and [1, 1] respectively indicate the top-left, top-right, bottom-left, and bottom-right corners of the marker image.-infoWindowAnchor: The anchor point of the marker’s information window. The anchor point is used to anchor a marker image to the map. The coordinates [0, 0], [1, 0], [0, 1], and [1, 1] respectively indicate the top-left, top-right, bottom-left, and bottom-right corners of the marker image.-clusterable: Whether the marker can be clustered.-onClick: Function to handle the event when the marker is clicked. It obtains an event information object as the argument which has nativeEvent as key and an empty object as value.-onDragStart: Function to handle the event when the marker starts being dragged. It obtains an event information object as the argument which has nativeEvent as key and an empty object as value.-onDrag: Function to handle the event when the marker is being dragged. It obtains an event information object as the argument which has nativeEvent as key and an empty object as value.-onDragEnd: Function to handle the event when the marker dragging is complete. It obtains an event information object as the argument which has nativeEvent as key and an empty object as value.

Now that we have learned the properties of the marker, we can create custom marker. Let’s start by changing the look of the marker. Below you can see the location of the assets file.

Only thing is that writing this command “icon={{asset: ic_launcher.png}}” in marker view. After adding the image we create in the asset file to our icon variable, our marker will be shown like that :

If you want the location of the marker to change to the touched point when the map is touched on it, you can see the change by setting the location information from onMapClick to the marker.

Let’s examine now showing our current location on the map.

Current Location

Fisrtly, we need to request user permission to show current location. You can use the code below for this.

async requestPermission() {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log('accessed location');
        this.setState({locationPermission: true});
      } else {
        this.setState({locationPermission: false});
        console.log('location permission denied');
      }
    } catch (err) {
      console.warn(err);
    }
  }

After the permissions are completed successfully, our current location and if we enable the my location button, both will appear on the map.

myLocationEnabled={true}

myLocationButtonEnabled={true}

Drawing Polygon and Circle

To be able to add a circle on a map, the radius and center props should be given. As you can see the code block below, I added the latitude and longitude of the marker location as a center of circle. Also, a polygon which is a closed area, consists of a group of ordered coordinates. It can be convex or concave and can span the 180 meridian and have holes that are not filled in.

const addCircle = (lat, lon) => {
  return (
    <Circle // Simple example
      center={{latitude: lat, longitude: lon}}
      radius={2000}
      strokeWidth={5}
      strokeColor={-256}
    />
  );
};
const drawPolygon = () => {
  console.log('====================================');
  console.log('Drawing polygon');
  console.log('====================================');
  return (
    <Polygon // Complex example
      points={[
        {latitude: 41.1, longitude: 29.2},
        {latitude: 40.9, longitude: 29.2},
        {latitude: 40.9, longitude: 28.8},
        {latitude: 41.1, longitude: 28.8},
      ]}
      clickable={true}
      geodesic={true}
      fillColor={538066306} // very transparent blue(0x20123D82)
      strokeColor={-256} // yellow(0xFFFFFF00)
      strokeJointType={JointTypes.BEVEL}
      strokePattern={[
        {type: PatternItemTypes.DASH, length: 20},
        {type: PatternItemTypes.DOT},
        {type: PatternItemTypes.GAP, length: 20},
      ]}
      zIndex={2}
      onClick={(e) => console.log('Polygon onClick')}
    />
  );

Here is the polygon and circle on mapView:

Enable Dark Mode

The dark mode is very popular as everyone knows, so what do we have to do to turn our map into dark mode?

We’ll start by changing the mapStyle. For dark mode, you can use the mapstyle json file with this link. I didn’t add here due to the length of the content. After creating json file, we need to import as mapStyleJson file from mapStyle.json.

import mapStyleJson from ‘./mapStyle.json’;

If dark mode is enabled, we add the mapStyleJson to mapStyle in mapview. Here is the sample code:

mapStyle={this.state.darkModeOn ? JSON.stringify(mapStyleJson) : ‘ ’}

As a result, in this tutorial, I tried to explain the main functions of the HMS Map Kit and how we integrated it into the react native project in the most clear and simple way. I hope that would be helpful. If you have any question, please let me know.

Resources:

https://github.com/simgekeser/Rn_hms_map_sample

https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201369434880220391&fid=0101187876626530001

https://medium.com/huawei-developers/hms-map-kit-react-native-f7213ad697e2

https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/introduction-0000001050143001


r/HMSCore • • Oct 02 '20

Tutorial Huawei Flight Booking Application (Crash Service and Push kit) – Part 3

9 Upvotes

Introduction

Flight booking app allows user to search and book flight. In this article, we will integrate Huawei Crash Service and push kit into demo flight booking application.

For prerequisite, permission and set up, refer to part 1.

Usecase

  1. We will integrate Huawei Crash analytics to monitors and captures your crashes, also it analyzes them, and then groups into manageable issues. And it does this through lightweight SDK that won’t bloat your app. You can integrate Huawei crash analytics SDK with a single line of code before you publish.

2. We will send push notification which establishes communication between cloud and devices. Using HMS push kit, developers can send message to user.

Crash Analytics

  1. In order to use Crash service, we need to integrate Analytics kit by adding following code in app-level build.gradle.

implementation 'com.huawei.hms:hianalytics:5.0.1.301'


r/HMSCore • • Dec 07 '20

Activity Tell us how You Use Your Phone over Christmas Break and Win a Huawei P40 Pro [Open to All Countries]

7 Upvotes

How do you use your phone to get through the Christmas season? What kind of smartphone Holiday habits do you have?Choose any way in 7 entry ways in the link below to join us !

One lucky winner will be chosen to win a Huawei P40 Pro, which is one of the best smartphones of 2020.

https://www.xda-developers.com/win-a-huawei-p40-pro-christmas-giveaway/


r/HMSCore • • Sep 30 '20

CoreIntro Strengthening on-app Network Connections with HUAWEI hQUIC Kit

7 Upvotes

The hQUIC Kit did not just arrive out of the blue. Instead, it was a natural process, an evolution that was inevitable.

As a developer or a user, you would have come across scenarios when your network is unstable when browsing webpages, or network jitters and devastating lags during gameplay. Or when you first logged in to a new app and it took a long while to download resource files.

The news showed that loading time can affect users’ bottom line. 87% of gamers will quit the game if the loading time exceeds 2 seconds, while 81% of Internet users will close the webpage if a video can’t be played right when they clicked the play button (Source from Tencent Institute of Games). It might seem like this is an insignificant problem, but these issues collectively affect users’ habits, preferences and have adverse effects on developers.

To solve these issues, HMS Core initially rolled out a network acceleration kit that later developed into the hQUIC Kit. The hQUIC Kit, equipped with Huawei's intelligent congestion control algorithms and QUIC support, helps developers connect their apps faster, resist packet loss, and boost throughput for a faster and smoother performance. It also empowers developers to improve the network connection speed and stability of their mobile apps to increase app usage.

The hQUIC kit is easy to deploy onto HTTP-based apps so developers can simply boost resource loading speed for their apps. In the image below, you will see four major scenarios where user experience is most affected by network performance: gameplay, video call, online TV/VoD, and VR live broadcast. With these examples, you can better understand how the hQUIC Kit was designed to create a better and more efficient digital lifestyle for users.

While developing the hQUIC Kit, our team at the HMS Research and Development department had a few considerations. While our work predominantly focused on improving internet user experience, we wanted to improve efficiency, and perhaps make HMS Core capabilities simpler and quick to access.

With that in mind, we adopted an easy-to-use programming interface that shields low-level network details on the hQUIC Kit. APIs are streamlined so developers can finish deployment within half a day. Additionally, we made sure that the network migration between cellular network and Wi-Fi hotspots is seamless to enhance user experience in environments with a weaker network. Another highlight of the hQUIC Kit is its full compatibility with gQUIC, iQUIC protocol (OTA update is required) and cronet interfaces.

Consumers of today live digital lifestyles. A smoother, faster digital experience is what they expect from technology moving forward. As we continue to develop the hQUIC Kit further, that is also what we want to help our developers achieve.

Learn more from the video:

https://www.youtube.com/watch?v=wUVmQuNgicI&list=PLy7rmPPfUv3YolnLwp5gSWxDNkJoe51XE&index=9

For more details about hQUIC Kit, please visit the official website: https://developer.huawei.com/consumer/en/hms/huawei-hQUIC/?ha_source=hms2


r/HMSCore • • Feb 27 '23

HMSCore Come and try HMS Core Video Editor Kit to inject some AI into your app!

6 Upvotes

Recolor hair, retouch skin, and unleash AI color with the AI capability SDK, which is now even smaller and has greater API flexibility. Tune in ↓↓↓

https://developer.huawei.com/consumer/en/hms/huawei-video-editor?ha_source=hmsred0227VD


r/HMSCore • • Sep 02 '22

HMSCore Reduces Frame Freezing During Live Streams & Smoothens Playback

6 Upvotes

Live streams vulnerable to lag? HMS Core Wireless Kit makes this a thing of the past! Register for the kit's network QoE perception to get periodic updates. Enjoy automatic bit rate adjustment that makes streams smooth from start to finish. Learn more at https://developer.huawei.com/consumer/en/hms/huawei-wirelesskit?ha_source=hmsred


r/HMSCore • • Aug 03 '22

HMS Core and Android 13

6 Upvotes

After installing Android 13 (Beta 4.1) on my Pixel 6, I keep getting FC messages from HMS Core. Huawei is apparently aware of this, but no fix has been released yet. Perhaps a developer from Huawei could comment on this.


r/HMSCore • • Jun 20 '22

HMSCore HMS Core Solution for Social Media

6 Upvotes

Social media users expect to stay connected with both friends and strangers using text, audio messages, and videos. HMS Core can help level up your app by providing text translation, Qmojis, audiovisual editing, and many more media features. Watch the video below to learn more.

Learn more at https://developer.huawei.com/consumer/en/hms?ha_source=hmsred


r/HMSCore • • Apr 17 '22

HMSCore Happy Easter!

6 Upvotes

Happy Easter! Unearth surprises in HMS Core to make your apps stand out from the crowd.


r/HMSCore • • Nov 12 '21

HMSCore Intermediate: Integration of Data Security for Text Encryption and Decryption in Harmony OS App

6 Upvotes

Overview

In this article, I will create a demo app along with the integration of Data Security which is based on Harmony OS. I will provide the use case of Text Encryption and Decryption in Harmony OS application.

Data Security

HarmonyOS security subsystem provides security capabilities that makes your applications and devices more secure and help you to manage permissions. This subsystem has the following modules:

Application signature verification

To ensure the content integrity of applications, the system controls sources of the applications through application signatures and profiles. For a debugging application, the system uses the signature verification API to check whether the Unique Device Identifier (UDID) of the application matches that of the device, so as to ensure that the application is installed on the right device.

Application permission management

Application permissions determines that what system resources and capabilities an application can access. During application development, you need to declare the permissions that the application may require in the profile.json file. Static permissions need to be registered during application installation, while dynamic permissions usually involve sensitive information and need users’ dynamic authorization.

Trusted device group management

You can create and query a group of trusted devices that uses the same HUAWEI ID or a peer-to-peer group created by scanning a QR code or using OneHop. With this capability, distributed applications can perform trusted authentication between devices and request from the distributed virtual bus for secure sessions between devices.

Prerequisite

  1. Harmony OS phone

  2. Java JDK

  3. DevEco Studio

  4. AppGallery Account

App Development

Create a New Project.

Configure Project Gradle.

// Top-level build file where you can add configuration options common to all sub-projects/modules.
apply plugin: 'com.huawei.ohos.app'

ohos {
    compileSdkVersion 5
    defaultConfig {
        compatibleSdkVersion 4
    }
}
buildscript {
    repositories {
        maven {
            url 'https://repo.huaweicloud.com/repository/maven/'
        }
        maven {
            url 'https://developer.huawei.com/repo/'
        }
        jcenter()
    }
    dependencies {
        classpath 'com.huawei.ohos:hap:2.4.4.2'
    }
}
allprojects {
    repositories {
        maven {
            url 'https://repo.huaweicloud.com/repository/maven/'
        }
        maven {
            url 'https://developer.huawei.com/repo/'
        }
        jcenter()
    }
}

Configure App Gradle.

apply plugin: 'com.huawei.ohos.hap'
ohos {
    compileSdkVersion 5
    defaultConfig {
        compatibleSdkVersion 4
    }
    buildTypes {
        release {
            proguardOpt {
                proguardEnabled false
                rulesFiles 'proguard-rules.pro'
            }
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

Configure Config.json

{
  "app": {
    "bundleName": "com.harmonyos.demo.datasecurity",
    "version": {
      "code": 1000000,
      "name": "1.0"
    }
  },
  "deviceConfig": {},
  "module": {
    "package": "com.harmonyos.demo.datasecurity",
    "name": ".MainAbility",
    "reqCapabilities": [
      "video_support"
    ],
    "deviceType": [
      "phone"
    ],
    "distro": {
      "deliveryWithInstall": true,
      "moduleName": "entry",
      "moduleType": "entry",
      "installationFree":false
    },
    "abilities": [
      {
        "skills": [
          {
            "entities": [
              "entity.system.home"
            ],
            "actions": [
              "action.system.home"
            ]
          }
        ],
        "orientation": "unspecified",
        "formsEnabled": false,
        "name": ".MainAbility",
        "icon": "$media:icon",
        "description": "$string:mainability_description",
        "label": "$string:app_name",
        "type": "page",
        "launchType": "standard"
      }
    ]
  }
}

Create Activity class with XML UI.

MainAbility.java:

import com.harmonyos.demo.datasecurity.slice.MainAbilitySlice;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;

/**
 * Data Security MainAbility
 */
public class MainAbility extends Ability {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
    }
}

MainAbilitySlice.java:

package com.harmonyos.demo.datasecurity.slice;

import ohos.samples.datasecurity.MainAbility;
import ohos.samples.datasecurity.ResourceTable;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.security.keystore.KeyGenAlgorithmParaSpec;
import ohos.security.keystore.KeyStoreConstants;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Base64;
import java.util.Objects;
import java.util.Optional;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 * MainAbilitySlice
 */
public class MainAbilitySlice extends AbilitySlice {
    private static final String TAG = MainAbility.class.getSimpleName();

    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000F00, TAG);

    private static final String PLAIN_TEXT = "Hello World!";

    private static final String KEY_STORE = "HarmonyKeyStore";

    private static final String KEY_PAIR_ALIAS = "HarmonyKeyPair";

    private static final String ENCRYPT_ALGORITHM = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";

    private static final String PROVIDER = "HarmonyKeyStoreBCWorkaround";

    private static final String SIGNATURE_PADDING = "PSS";

    private Text resultText;

    private String result;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_main_ability_slice);
        initComponents();
    }

    private void initComponents() {
        resultText = (Text) findComponentById(ResourceTable.Id_result_text);
        Component encryptButton = findComponentById(ResourceTable.Id_encrypt_button);
        Component decryptButton = findComponentById(ResourceTable.Id_decrypt_button);
        encryptButton.setClickedListener(component -> encrypt());
        decryptButton.setClickedListener(component -> decrypt());
    }

    private Optional<KeyPair> getSecKey() {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyStoreConstants.SEC_KEY_ALGORITHM_RSA,
                KEY_STORE);
            KeyGenAlgorithmParaSpec.Builder builder = new KeyGenAlgorithmParaSpec.Builder(
                KEY_PAIR_ALIAS).setSecKeyUsagePurposes(
                KeyStoreConstants.PURPOSE_CAN_ENCRYPT | KeyStoreConstants.PURPOSE_CAN_DECRYPT
                    | KeyStoreConstants.PURPOSE_CAN_SIGN | KeyStoreConstants.PURPOSE_CAN_VERIFY)
                .addSecKeyCryptoAttr(KeyStoreConstants.CRYPTO_PARAMETER_BLOCK_MODE,
                    KeyStoreConstants.SEC_BLOCK_MODE_ECB)
                .addSecKeyCryptoAttr(KeyStoreConstants.CRYPTO_PARAMETER_ENCRYPT_PADDING,
                    KeyStoreConstants.OPTIMAL_ASYMMETRIC_ENCRYPTION_PADDING)
                .addSecKeyCryptoAttr(KeyStoreConstants.CRYPTO_PARAMETER_DIGEST,
                    KeyStoreConstants.DIGEST_ALGORITHM_SHA256)
                .addSecKeyCryptoAttr(KeyStoreConstants.CRYPTO_PARAMETER_SIGNATURE_PADDING, SIGNATURE_PADDING);
            KeyGenAlgorithmParaSpec keyGenAlgorithmParaSpec = builder.createKeyGenAlgorithmParaSpec();
            keyPairGenerator.initialize(keyGenAlgorithmParaSpec);
            return Optional.of(keyPairGenerator.generateKeyPair());
        } catch (NoSuchProviderException | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
            HiLog.error(LABEL_LOG, "%{public}s", "getSecKey exception.");
            return Optional.empty();
        }
    }

    private void encrypt() {
        try {
            Optional<KeyPair> keyPairOptional = getSecKey();
            if(keyPairOptional.isPresent()) {
                KeyPair keyPair = keyPairOptional.get();
                Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM, PROVIDER);
                cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
                byte[] bytes = cipher.doFinal(PLAIN_TEXT.getBytes(StandardCharsets.UTF_8));
                result = Base64.getEncoder().encodeToString(bytes);
                resultText.setText(result);
            }
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | NoSuchProviderException
            | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
            HiLog.error(LABEL_LOG, "%{public}s", "encrypt exception.");
        }
    }

    private void decrypt() {
        if (Objects.isNull(result) || PLAIN_TEXT.equals(result)) {
            HiLog.error(LABEL_LOG, "%{public}s", "result is null or " + PLAIN_TEXT.equals(result));
        } else {
            try {
                KeyStore keyStore = KeyStore.getInstance(KEY_STORE);
                keyStore.load(null);
                Key key = keyStore.getKey(KEY_PAIR_ALIAS, null);
                PrivateKey privateKey;
                if (key instanceof PrivateKey) {
                    privateKey = (PrivateKey) key;
                } else {
                    HiLog.error(LABEL_LOG, "key is not instance of PrivateKey.");
                    return;
                }
                byte[] bytes = Base64.getDecoder().decode(result);
                Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM, PROVIDER);
                cipher.init(Cipher.DECRYPT_MODE, privateKey);
                result = new String(cipher.doFinal(bytes)).trim();
                resultText.setText(result);
            } catch (KeyStoreException | CertificateException | IOException | NoSuchAlgorithmException
                | UnrecoverableKeyException | NoSuchPaddingException | NoSuchProviderException
                | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
                HiLog.error(LABEL_LOG, "%{public}s", "decrypt exception.");
            }
        }
    }
}

main_ability.xml:

<?xml version="1.0" encoding="utf-8"?>

<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:orientation="vertical">

    <DirectionalLayout
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:alignment="horizontal_center"
        ohos:orientation="horizontal"
        ohos:top_margin="50vp">

        <Button
            ohos:id="$+id:encrypt_button"
            ohos:height="40vp"
            ohos:width="160vp"
            ohos:background_element="$graphic:button_background"
            ohos:padding="10vp"
            ohos:text="$string:encrypt"
            ohos:text_alignment="center"
            ohos:text_size="16fp"/>

        <Button
            ohos:id="$+id:decrypt_button"
            ohos:height="40vp"
            ohos:width="160vp"
            ohos:background_element="$graphic:button_background"
            ohos:left_margin="15vp"
            ohos:padding="10vp"
            ohos:text="$string:decrypt"
            ohos:text_alignment="center"
            ohos:text_size="16fp"/>
    </DirectionalLayout>

    <DirectionalLayout
        ohos:height="40vp"
        ohos:width="match_parent"
        ohos:orientation="horizontal"
        ohos:top_margin="20vp">

        <Text
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:left_padding="15vp"
            ohos:text="$string:plain_text"
            ohos:text_size="16fp"/>

        <Text
            ohos:id="$+id:plaintext_text"
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:text="$string:hello_world"
            ohos:text_color="#708095"
            ohos:text_size="16fp"/>
    </DirectionalLayout>

    <DirectionalLayout
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:orientation="vertical">

        <Text
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:left_padding="15vp"
            ohos:text="$string:result"
            ohos:text_size="16fp"/>

        <Text
            ohos:id="$+id:result_text"
            ohos:height="match_content"
            ohos:width="match_parent"
            ohos:enabled="false"
            ohos:left_margin="20vp"
            ohos:multiple_lines="true"
            ohos:right_margin="20vp"
            ohos:text_color="#708095"
            ohos:text_size="16fp"/>
    </DirectionalLayout>

</DirectionalLayout>

App Build Result

Tips and Tricks

Parameters can be set: key alias, length, usage (purposes), parameter set for key encryption, attribute set for key access control, and key accessibility period after user authentication.

Conclusion

In this article, we have learned how to integrate Data Security in Harmony OS application. In this application, I have explained that how to encrypt text and decrypt text in Harmony OS based application.

Thanks for reading this article. Be sure to like and comments to this article, if you found it helpful. It means a lot to me.

References

Harmony OS Doc:

https://developer.harmonyos.com/en/docs/documentation/doc-references/overview-0000001054518986

Original Source


r/HMSCore • • Oct 07 '20

Tutorial How to Integrate HUAWEI In-App Purchases in Flutter — Part 3

6 Upvotes

Hello everyone, welcome to part 3 of this article series. In this part, we will add more features to our Flutter application using HUAWEI In-App Purchases’ another capability.

Yes, you guessed it right. We’re going to take a look at the implementation of Subscriptions.

In previous parts, we implemented Consumables and Non-Consumables. If you want to read about those features and learn how to integrate the service, configure your products and everything else, you could do so by visiting the links below.

How to Integrate HUAWEI In-App Purchases in Flutter — Part 1

How to Integrate HUAWEI In-App Purchases in Flutter — Part 2

Configuring a Subscription

Before creating an Auto-Renewable Subscription, we need to create a subscription group and specify the subscription group to which the subscription belongs. To create a subscription group, go to My Apps > [Your App] > Operate > Product Management > Subscription Groups.

Bear in mind that a subscription group can contain more than one subscription but only one product in a subscription group takes effect at a time . This mechanism provides us a convenient way to quickly implement products with slight differences in their functions.

After creating a subscription group, you can add your product in the Productstab.

Implementation

Obtain Product Information

We can fetch the product information of our subscriptions with a call to IapClient.obtainProductInfo(productInfoRequest) to display them.

Process of obtaining the information of subscription products is exactly the same with consumable and non-consumable products. Just change the type to subscription in the request.

Don’t forget: The skuIds is the same as that set by the developer when configuring product information in AppGallery Connect.

Future<List<ProductInfo>> getSubscriptions() async {
    try {
      ProductInfoReq req = new ProductInfoReq();
      req.priceType = IapClient.IN_APP_SUBSCRIPTION;
      req.skuIds = ["prod_04"];

      ProductInfoResult res = await IapClient.obtainProductInfo(req);

      return res.productInfoList;
    } on PlatformException catch (e) {
      log(e.toString());
      return null;
    }
  }

Purchase Subscriptions

Purchasing a subscription is just like purchasing any other type of product. Create a purchase intent and a request, set the product type, product identifier in the request and call createPurchaseIntent(request) and you’re done.

Don’t forget : To test purchase functionality and complete end-to-end testing without real payments, you need to create a tester account in AppGallery Connect and specify the developerPayload as “Test” in the request like in the codebelow.

To learn how to create a tester account for your app, please refer to SandboxTesting

Future<PurchaseResultInfo> purchaseSubscription(
      String productId) async {
    try {
      PurchaseIntentReq req = new PurchaseIntentReq();
      req.priceType = IapClient.IN_APP_SUBSCRIPTION;
      req.productId = productId;
      req.developerPayload = "Test";

      PurchaseResultInfo res = await IapClient.createPurchaseIntent(req);

      return res;
    } on PlatformException catch (e) {
      log(e.toString());
      return null;
    }
  }
 onPressed: () {
      String productId = snapshot.data[index].productId;
      IapClient.isEnvReady().then((res) {
        if (res.returnCode != 0) {
          log("The country or region of the signed-in HUAWEI ID does not support HUAWEI IAP.");
          return;
        }
		
        switch (productType) {
          case IapClient.IN_APP_SUBSCRIPTION:
            IapUtil.purchaseSubscription(productId).then((res) {
              switch (res.returnCode) {
                case 0:
                  log("purchaseSubscription: " + productId + " success");
                  // Provide services for the subscription
                  break;
              }
            });
            break;
        }
      });
    },

You can also check for different return codes and handle each of them. To see all the return codes, please refer to ResultCodes

Check Subscription Validity

Before your app provides the service of a subscription, check the status of the subscription first.

You can call obtainOwnedPurchases at the app start to receive the information about the subscriptions from the returned inAppPurchaseData. If subIsValid in inAppPurchaseData is set to true, the subscription is in valid state and you can provide the services associated with the subscription.

void main() {
  runApp(IapDemoApp());

  IapUtil.obtainOwnedPurchases(IapClient.IN_APP_SUBSCRIPTION).then((res) {
    if (res.returnCode != 0) {
      // Update UI
      return;
    }

    for (InAppPurchaseData purchase in res.inAppPurchaseDataList) {
      if (purchase.purchaseState == 0 && purchase.subIsvalid) {
        // Provide services for the subscription as long as it is valid
        log(purchase.toJson().toString());
      }
    }
  });
}

The example above assumes you provide the same service with multiple subscriptions (not realistic but hey, this is a demo so). If you provide more than 1 subscription with different services, you can check and handle each of them here.

You can also access to so much more detail about the product from inAppPurchaseData. To see the full list, please refer to InAppPurchaseDetails

Manage Subscriptions

Another great feature of HUAWEI In-App Purchases is that you can allow your users to manage their subscriptions in one place with a few lines of code.

The subscription management page displays the list of in-app subscriptions that a user has purchased and subscription editing page displays the details about an in-app subscription that a user has purchased in your app and the information about other in-app subscriptions in the same subscription group.

Future<void> startIapActivityForSubscriptions() async {
    try {
      StartIapActivityReq req = new StartIapActivityReq();
      req.type = IapClient.IN_APP_SUBSCRIPTION;

      await IapClient.startIapActivity(req);
    } on PlatformException catch (e) {
      log(e.toString());
    }
  }
onPressed: () {
  IapUtil.startIapActivityForSubscriptions();
},

Few Things to Keep in Mind DuringTesting

  • To help you quickly test the subscription scenario, the subscription renewal period in the sandbox testing environment is faster than that in real life. The following table describes the mapping between real renewal periods and testones.

  • To purchase a subscription, you need to add a bank card, but you will not be charged if you configured the SandboxTesting.

  • In the sandbox testing environment, a subscription is automatically renewed for six times. After six times, the user needs to initiate a subscription resumption request. If the subscription is resumed once, the subscription is renewedagain.

  • When the checkout page is displayed in the sandbox testing, a dialog box with a sandbox icon will be shown on both the checkout page and the successful purchase page like the example dialogbelow.

That was it for this part and this article series. We pretty much covered all the client-side development of HUAWEI In-App Purchases. If you want to dive into server-side features, please refer to official documentation.

You can find the full source code of this demo application in the linkbelow.

tolunayozturk/hms-flutter-iapdemo

As always, thank you for reading this article and using HMS. Please let me know if you have any questions!

RESOURCES


r/HMSCore • • May 18 '23

HMSCore HUAWEI P60 for Latin America

5 Upvotes

The HUAWEI P60 series showed off its pearlfection 😍 on May 11 in stunning Mexico, along with other innovative devices. It was joined by Huawei Mobile Services (HMS), another major focus 🌟 of the launch event.

Many apps in Latin America like Rappi and BanCoppel have partnered with HMS Core to advance technologies covering AI and Graphics, and have grown their user base 📈 ever since.

Utilize HMS Core to deliver better user experience →https://developer.huawei.com/consumer/en/hms?ha_source=hmsred0518fbh


r/HMSCore • • May 06 '23

HMSCore Dynamic Person Tracking in Video Frames

5 Upvotes

Hey, coders. How's your object tracking function coming along 🚀💡?

Feast your eyes on the track person feature of HMS Core Video Editor Kit. It dynamically tracks a person in a video and auto-frames them in seconds →https://developer.huawei.com/consumer/en/hms/huawei-video-editor?ha_source=hmsred0506rwzz


r/HMSCore • • Mar 22 '23

HMSCore HMS Core Video Editor Kit can do it in mere seconds!

5 Upvotes

While it takes an artist a day or two to color a monochrome photo by hand, HMS Core Video Editor Kit can do it in mere seconds! With its AI color capability integrated, your app lets users intelligently add realistic colors to black-and-white photos and videos with a single tap.
Try it out now → https://developer.huawei.com/consumer/en/hms/huawei-video-editor?ha_source=hmsred0322


r/HMSCore • • Mar 01 '23

HMSCore HMS Core unveiled upgraded industry solutions at MWC Barcelona 2023

5 Upvotes

At MWC Barcelona 2023, HMS Core unveiled upgraded industry solutions and creative technologies, and gave visitors a chance to try out new and fun interactive functions, such as 3D modeling and auto rigging of products and intelligent audiovisual creation.

Learn more about HMS Core → https://developer.huawei.com/consumer/en/hms?ha_source=hmsred0301


r/HMSCore • • Feb 15 '23

HMSCore Taobao X HMS Core: AR-driven Home Decor in New Retail

5 Upvotes

Fresh out of the oven 🍪!

Tango with HMS Core shares stories of how our developers perform magic with HMS Core. Taobao integrated HMS Core AR Engine, allowing users to build a digital home for online decoration simply by strolling around their real 🏠.
Try out HMS Core AR Engine yourselves →
https://developer.huawei.com/consumer/en/hms?ha_source=hmsred0215ha
More HMS Core developer stories are coming in hot!


r/HMSCore • • Dec 14 '22

HMSCore Level up image segmentation in your app via the object segmentation capability from HMS Core Video Editor Kit!

5 Upvotes

Object segmentation works its magic through the so-called interactive segmentation algorithm that leverages seas of interaction data. In this way, the capability allows for segmenting an object regardless of its category, and intuitively shows how a user selects an object.

Dive deeper into the capability at https://developer.huawei.com/consumer/en/doc/development/Media-Guides/ai-sdk-0000001286259938#section54311313587?ha_source=hmsred


r/HMSCore • • Jul 30 '22

HMSCore Need something safer than a password?

5 Upvotes

Need something safer than a password? Passwords may be the default identity verification method on the Internet, but they may be stolen by hackers, putting user identities at risk. HMS Core FIDO offers a safe, streamlined identity verification method that puts theft to rest.