Huawei Developers
Published in

Huawei Developers

Intermediate : How to Create and Communicate with Service Ability in Harmony OS

Introduction

This application helps to create Service Ability (which runs on main thread) and sending data from Service Ability to Page Ability. It uses thread to get data from server inside Service Ability and then passes the same data to UI.

Key features of this application:

  1. Create Service Ability.
  2. Create Thread inside Service Ability.
  3. Get the data from network inside Thread.
  4. Connect Page Ability with Service Ability and get data on Page Ability.

Requirements:

  1. HUAWEI DevEco Studio
  2. Huawei Account

Development:

Step 1: Create ServiceAbility which extends Ability.

Step 2: Register your ServiceAbility inside config.json file inside abilities array.

Step 3: Add Internet permission inside module.

Step 4: Create thread inside ServiceAbility onStart() method and get the data from network inside thread.

Step 5: Create MyRemoteObject inside ServiceAbility which extends LocalRemoteObject class to set the response data.

Step 6: Return the object of MyRemoteObject class when ServiceAbility connection is success.

ServiceAbility.Java

Step 7: Create the ability_main.xml.

Step 8: Implement the click listener inside OnStart() of MainAbility for connecting with ServiceAbility and after connection is success, update the UI.

Now Implementation part done.

Result

Tips and Tricks
Please add device type in config.json.

Conclusion

In this article, we have learnt about creating and registering a Service Ability, Creating thread inside Service Ability, getting the response from service inside thread, and how to connect Page Ability with Service Ability.
Thanks for reading!

Reference

Create Service Ability

Thread Management

Network Management

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store