A Novice Journey of integrating Huawei Video Kit feat. Node js Local Server (An Educational Video Application)

Sanghati Mukherjee
Nov 6 · 8 min read
Image for post
Image for post

Introduction

HMS Video Kit allow us to play video by using a URL or multiple URLs that contain an address of a video. The latest version of this kit allow us to playback videos but in the later version it will support both editing and hosting of videos.

This service helps us to build a superb video experience for our app users.

  1. The service can be used in a news app that contains small videos of the reported incident.
  2. The service can be used as a video editing app.
  3. The service can be used as a promotion video in your application.
  4. The service can be used as an educational video related application.

In this article we will be working on one of the use case and that is education video related application. For that we need two major players in any software development and that is server and client.

Demo

Image for post
Image for post

Server Side (Node Server)

  1. We must have latest version of Node installed.
  2. We must have latest version of Visual Studio Code installed.
  3. Laptop/desktop and Huawei mobile device must share same Wi-Fi connection.

1. Express js is a Node js web application server framework, designed for building single-page, multi-page, and hybrid web applications. It is the de facto standard server framework for node.js.

We don’t have to repeat same code over and over again using Express js. Node.js is a low-level I/O mechanism which has an HTTP module. If you just use an HTTP module, a lot of work like parsing the payload, cookies, storing sessions, selecting the right route pattern based on regular expressions will have to be re-implemented. With Express.js, it is just there for us to use.Express.js basically helps us manage everything, from routes, to handling requests and views.

2. Request module is by far the most popular (non-standard) Node package for making HTTP requests. Actually, it is really just a wrapper around Node’s built in http module, so we can achieve all of the same functionality on your own with http, but request just makes it a whole lot easier.

const request = require('request');
request(' https://developer.huawei.com/consumer/en/', function(err, res, body) {
console.log(body);
});

The code above submits an HTTP GET request to developer.huawei.com and then prints the returned HTML to the screen. This type of request works for any HTTP endpoint, whether it returns HTML, JSON, an image, or just about anything else.The first argument to request can either be a URL string, or an object of options. Here are some of the more common options you’ll encounter in our application:

a) url: The destination URL of the HTTP request

b) method: The HTTP method to be used (GET, POST, DELETE, etc.)

c) headers: An object of HTTP headers (key-value) to be set in the request

d) form: An object containing key-value form data

First we need to find a space in our machine and create a folder. We can name the folder whatever we want. Open Visual Studio Code, navigate to particular folder location which we created using cd command in the terminal of VS code. Run the below command to create package.json file.

npm init

Answer the questions presented, and you will end up with a package.json that looks like this:

{"name": "android-node-server","version": "1.0.0","description": "It is a server for HMS Push Notification Kit","main": "app.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"author": "Sanghati","license": "ISC"}

We need to run the above command when we start a new project. Also whatever tools we install in this project, a dependency will be added in the package.json file and we use the below command to install our dependencies in node_modules folder.

npm install

We may need to run this every time we manually add a dependency to our package.json file.

We run the below command to install Express js in our project.

npm install express –save

— save, will ensure to add express dependency to our package.json file.

To create app.js file using VS code terminal we need touch. Touch command creates an empty file if it doesn’t exist. Run the below command to create app.js file.

npm install -g touch-cli
touch app.js

Open app.js in our favourite text editor, in my case VS Code. Import Express into our application:

const express = require('express');
const app = express();

After importing Express, we have to create a server where applications and API calls can connect. We can do that with Express listen method.

app.listen(8080, () => {
console.log('app working on 8080')
});

We can test your server by running the below command.

node app.js

After running the above command we should see this:

app working on 8080

We will get tired of restarting our server every time we make any changes. We can fix this problem by using a package called Nodemon. Run below command to install nodemon globally.

npm install -g nodemon

Now, to run the project we will run below command instead node app.js.

nodemon app.js

Now let’s create a route that we can access in the browser. Browsers only serve pages using a GET request, so we need to create a route using Express get method like this:

app.get('/', function(req, res) {res.send("Yep it's working");});

If we visit http://localhost:8080 on our web browser, we should see this:

Image for post
Image for post

For our application to receive POST requests, we will need a package called body-parser, which we can install by running:

npm install body-parser --save

body-parser extract the entire body portion of an incoming request stream and exposes it on req.body.

Now, we can import body-parser into our application like this:

const express = require('express');
const app = express();
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
//Body Parser ...app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

Middleware functions can access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers, etc. Here we have used it only for a specific path.

app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/img'));
app.use(express.static(__dirname + '/videos'));

We need to place all our videos in a video server folder as shown below:

Image for post
Image for post

We will be using GET HTTP verb to send all videos from local server to android client. Let’s create our get route.

Tips: Replace the link of videos and images with your respective machine IPV4 address and port number. Port number is the number your local server is running.

Client Side (Android Native)

  1. Must have a Huawei Developer Account.
  2. Must have a Huawei phone with HMS 4.0.0.300 or later.
  3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
  1. First we need to create an app or project in the Huawei app gallery connect.
  2. Provide the SHA Key and App Package name of the android project in App Information Section.
  3. Provide storage location in convention section under project setting.
  4. After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the json file in the app folder of the android project.
  5. Copy and paste the maven url inside the repositories of buildscript and allprojects respectively (project build.gradle file)

maven { url ‘http://developer.huawei.com/repo/' }

6. Copy and paste the class path inside the dependency section of project build.gradle file.

classpath ‘com.huawei.agconnect:agcp:1.3.1.300’

7. Copy and paste the plugin in the app build.gradle file

apply plugin: ‘com.huawei.agconnect’

8. Copy and paste the library in the app build.gradle file dependencies section.

implementation ‘com.huawei.hms:videokit-player:1.0.1.300’

9. Put the below permission in AndroidManifest file.

<uses-permission android:name=”android.permission.INTERNET” />
<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE” />
<uses-permission android:name=”android.permission.REQUEST_INSTALL_PACKAGES” />
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />
<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE” />

10. Now Sync the gradle.

We need Retrofit in order to call our restful APIs. Include the following dependencies in app build.gradle file.

implementation ‘com.squareup.retrofit2:retrofit:2.8.1’
implementation ‘com.squareup.retrofit2:converter-gson:2.5.0’

Create a new java class and name it Videos. Open Videos class, copy and paste below code:

Create a new Interface class and name it RetrofitInterface. Open the class, copy and paste below code:

Create a retrofit instance in the MainActivity class and get the list of all videos from local server as shown below:

Tips: Replace the BASE_URL with your machine IPV4 address with local server port number as shown below:

private String BASE_URL ="http://YOUR_IPV4_address:8080";

Use SimpleAdapter with ListView to show all the list as shown below:

First we need to implement a class that inherits from Application. In onCreate() method we need to initialize WisePlayerFactory.initFactory() of the WisePlayer SDK. This class is primarily used for initialization of global state before the first Activity is displayed.

Tips: Do not forget to put the name of your application class in the AndroidManifest file as show below:

There are two widgets in which WisePlayer use to play the videos:

1. SurfaceView widget

2. TextureView widget

We will be using SurfaceView widget in our layout as shown below:

Tips: Create a ShowVideo activity class and use the above code in the respective ShowVideo layout.

In the ShowVideo class, implement WisePlayer.ReadyListener and Callback APIs as shown below:

import android.view.SurfaceHolder.Callback;
import com.huawei.hms.videokit.player.WisePlayer;

public class ShowVideo extends AppCompatActivity implements WisePlayer.ReadyListener, Callback

Initialize SurfaceView in onCreate() method and add layout listeners as show below:

surfaceView = findViewById(R.id.surface_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

A WisePlayerFactory instance is returned from Application class when the WisePlayer initialization is successful.

WisePlayer player = HMSVideoKitApplication.getWisePlayerFactory().createWisePlayer();

Set the playback parameters as shown below:

player.setVideoType(PlayerConstants.PlayMode.PLAY_MODE_NORMAL);
player.setBookmark(0);
player.setCycleMode(PlayerConstants.CycleMode.MODE_NORMAL);

In the above code, the setVideoType indicates that whether we want to play the video with audio or only audio. The setBookmark helps us to start the video from a certain time like we can start video after 30 seconds. The setCycleMode helps us to repeat the video again.

We can set one or multiple URL’s video by using setPlayUrl method as show below:

player.setPlayUrl(getIntent().getStringExtra("url"));

Set a view to display the video as shown below:

@Override
public void surfaceCreated(SurfaceHolder holder) {
player.setView(surfaceView);
}
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
player.start();
}
});
btnPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
player.pause();
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
player.stop();
}
});

Final Code

Tricks

An error will occur while using local server with android client and that is “CLEARTEXT communication to 192.168.1.4 not permitted by network security policy”. In order to avoid this error put android:usesCleartextTraffic=”true” in AndroidManifest application section.

Conclusion

We learn how to create a local server, create API to call the list of all the videos on the client side and show the video using HMS Video Kit. It does not take more than a day to integrate the entire scenario. I hope after reading this article we will get to see more beautiful application in AppGallery.

Feel free to comment, share and like the article. Also you can follow me to get awesome article like this every week.

For more reference

https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050439577

Huawei Developers

Huawei Developers

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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