Android Uni-App encapsulates native plug-ins

preface

According to the needs of the majority of users, we need to package the SDK of anyRTC into UNI-APP for use and realize audio and video calls. This article illustrates how to package native plug-ins and the next chapter uni-app for voice and video calls.

Developer’s Official website

1. What is uni-app?

A Vue. Js development of all front-end application framework, developers write a set of code, can be published to ios, Android, H5, as well as a variety of small programs (wechat/Alipay/Baidu/Toutiao /QQ/ Dingding) and other platforms.

If you don’t already know what Uni-app is: Click here: this article illustrates examples.

2. The characteristics of the uni – app

  • Cross-platform more

    • Truly achieve “one set of code, multiple distribution”!
    • Conditional compilation: Gracefully call different platform features in one project!
  • Good running experience

    • Components, API and wechat applet consistent
    • Compatible with weeX native rendering
  • Learning costs are low through the technology stack

    • Vue syntax, wechat applet API
    • Embedded mpvue
  • Open ecology, richer components

  • Third-party packages can be installed using NPM

  • Support wechat small program custom components and SDK

  • Compatible with MPVUE components and projects

  • App side support and native mixed coding

  • DCloud will publish the plug-in marketplace

3. Uni-app encapsulates native plug-ins

3.1 Android Offline SDK Download:

Click on the download, both SDKS are available.

Download complete, decompress standby:

3.2 Creating an Android Project

Open Android Studio and create a No Activity project. On the menu bar, choose File>New>New Project

Next: Enter the project name, package name, and API Level.

Then Finish and move it to the Project view for better use. Next, create the developed Module.

Click File > New > New Module.

Then select Android Library and click Next:

To customize the Library name and package name, click Finish

The following view is created:

Build. Gradle in the testPlugin project, comment out the dependencies generated in the native dependencies section, and add the dependencies required by uni-app:

CompileOnly "com. Android. Support: recyclerview - v7:28.0.0" compileOnly "com. Android. Support: support - v4:28.0.0" compileOnly "Com. Android. Support: appcompat - v7:28.0.0" implementation 'com. Alibaba: fastjson: 1.1.46. Android' implementation 'com. Facebook. Fresco ": the fresco" : 1.13.0'Copy the code

The addition is completed as shown below:

In addition, import the uniapp-release-aar plugin, which is the main library on which the extension Module depends

Back in the build.gradle of the testPlugin you just created, do the configuration required to import the AAR:

Add: put outside android{}

repositories {
    flatDir {
        dirs 'libs'
    }
}
Copy the code

Then add to dependencies:

compileOnly fileTree(dir: '.. /app/libs', include: ['uniapp-release.aar'])Copy the code

Add completed, as shown below:

Then Sync Now!

3.3 Development of native plug-ins

Using extension Module as an example, create the TestModule class as shown below:

Module extension Notes:

Write a small demo:

import android.util.Log; import com.alibaba.fastjson.JSONObject; import com.taobao.weex.annotation.JSMethod; import com.taobao.weex.bridge.JSCallback; import com.taobao.weex.common.WXModule; public class TestModule extends WXModule{ String NAME="name"; String AGE ="age"; @jsMethod (uiThread = true) public void testText(JSONObject options, JSCallback callBack){log. e("TestModule", "successfully called! ); String name =options.getString(NAME); String age =options.getString(AGE); JSONObject data =new JSONObject(); if (name ! =null && ! name.isEmpty() && age ! =null && ! age.isEmpty()){ int _age =Integer.parseInt(age); If (_age < 0 | | _age > 30) {data. The put (" code ", "unqualified!" ); }else { age=(_age>0 && _age<10) ? "0"+age:age; Data. put("code"," qualified :"+" name _"+name+", age _"+age); }}else {data.put("code"," input invalid!") ); } callBack.invoke(data); }}Copy the code

3.3.1 Registering plug-ins:

Method 1:

Create the Assets folder in app> SRC >main

Create the dcloud_uniplugins.json file in app> SRC >main>assets and add:

{
  "nativePlugins": [
    {
      "plugins": [
        {
          "type": "module",
          "name": "Test-Module",
          "class": "com.test.testplugin.TestModule"
        }
      ]
    }
  ]
}
Copy the code

Method 2:

To create the Module extension testPlugin, create class TestModule_AppProxy under SRC >main> Java > plug-in package name (in this case com.test.testPlugin)

To implement the AppHookProxy interface for the TestModule_AppProxy class, add weeX registration parameters to the onCreate () method or fill in the logic that the plug-in needs to be initialized at startup.

In the hooksClass node, fill in the full name of the entity class that you created to implement the AppHookProxy interface. (Note: some initialization requirements can be added here, and there is no need to integrate the AppHookProxy interface.)

After registration, start packaging the plug-in

3.3.2 Packaging Plug-ins:

Go to Gradle>testplugin>Tasks> Other and double-click assembleRelease. Wait for the AAR file to compile the extension Module

Note: The official documentation is

choose

Gradle– > Plug-in Module –>Tasks– > Build –>assembleRelease Compiles the AAR file of the Module

AssembleRelease and assembleDebug are moved to the other directory in the new version of AndroidStudio.

Outputs >aar (testPlugin >build>outputs> AAR

4.HBuilderX imports and uses native plug-ins

Create the uni-app default project TestModule

Refer to the directory specification in the official documentation, and place the newly packaged plug-in under nativePlugins > Plug-in folder name (in my case, test-Module) > Android. Create the plug-in step by step without the relevant directory.

Create package.json — UNI native plugin description file and place it in the plugin folder name directory alongside the Android folder

Note: The plug-in id must be registered in the plugins of the corresponding Android and ios nodes, which is consistent with the value of the name field. The class under name is the class name of the registered plug-in.

Here because only Android plug-in, I will delete all ios nodes, here direct comments are invalid.

One other thing to note is that the plug-in id must be the same as the plug-in folder name, otherwise the cloud packaging will prompt the plug-in to be invalid: the plug-in does not exist in the nativePlugins directory.

Configure the native App plug-in in manifest.json

Check and confirm

Parameters Information is configured based on requirements

Next, make some changes to the index.vue file in your project (in the pages>index directory) in HBuilderX to test the native plug-in you developed later.

<template> <view class="container"> name <input V-model ="name" placeholder=" placeholder "> Placeholder = "click here to edit the age" > < br > < button type = "default" @ click = "test" > submit < / button > < view > {{name}} < / view > < view > {{age}} < / view > <view>{{ result }}</view> </view> </template> <script> var testModule = uni.requireNativePlugin("Test-Module"); Export default {data() {return {name:"", age:"", result:" not submitted yet "}}, methods: {the test () {testModule. TestText ({' name ': this name,' age ': this. Age,}, (ret) = > {this. Result = "submit feedback []" + ret. Code; }) } } } </script>Copy the code

5. Run the project

Pack custom base:

Run (R)> Run to phone or emulator (N)> Make custom Debug Dock (P)

Configure App cloud packaging information:

Cloud packaging:

Submit to cloud server:

Packing successfully:

After successfully packing, you need to ensure that the custom debug base function is enabled in the following position:

Start the emulator, or run it on a real machine:

Enter the test item:

Enter the name Tom and age 9 (< 0 and < 10) and click Submit

Feedback submission results

Change the age to 31 (the plugin sets the age range from 0 to 30) and give the following feedback

So, the test is successful!

6. Offline packaging test

6.1 configuration AndroidManifest. XML

Configure the androidmanifest.xml file ** in app**> SRC >main

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.test.nativeplugin"> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"  /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.REORDER_TASKS" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <application android:name="io.dcloud.application.DCloudApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:hardwareAccelerated="true" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name="io.dcloud.PandoraEntry" android:configChanges="orientation|keyboardHidden|keyboard|navigation" android:label="@string/app_name" android:launchMode="singleTask" android:hardwareAccelerated="true" android:theme="@style/TranslucentTheme" android:screenOrientation="user" android:windowSoftInputMode="adjustResize" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="io.dcloud.PandoraEntryActivity" android:launchMode="singleTask" android:configChanges="orientation|keyboardHidden|screenSize|mcc|mnc|fontScale|keyboard" android:hardwareAccelerated="true" android:permission="com.miui.securitycenter.permission.AppPermissionsEditor" android:screenOrientation="user" android:theme="@style/DCloudTheme" android:windowSoftInputMode="adjustResize"> <intent-filter> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <action android:name="android.intent.action.VIEW" /> <data android:scheme="h56131bcf" /> </intent-filter> </activity> <! - the provider node must be added - > < provider android: name = "io.dcloud.com mon. Util. DCloud_FileProvider" Android: authorities = "com. Test. Nativeplugin. Dc. Fileprovider" / / into your package name in front of the android: exported = "false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/dcloud_file_provider" /> </provider> </application> </manifest>Copy the code

6.2 Importing Packaged Resources

** Enter the downloaded Android offline SDK folder in the directory **

Latest \2.9.8\[email protected]_20201111\SDK\libs

  • lib.5plus.base-release.aar

  • [email protected] * * * *

  • * * * * msa_mdid_1. 0.13. The aar

  • **********uniapp-release.aar

Four files, copy to custom new folder for easy use

In the latest catalogue \ 2.9.8 \ [email protected]_20201111 \ SDK \ assets

Go to the data folder and open it to find the following files.

And above aar package in the same file, easy access!

6.3 Offline Packaging

As shown in the figure, choose Distribution (P) option > Native App-Local Packaging (L) and select Generate Local Packaged APP Resources (R).

If the export is successful, copy the folder with your project ID name along the path and put it in the folder defined in the previous step for easy use.

Put the offline packaged files in the same directory as the above files for easy access! My is __UNI__179390F

6.4 Configuring Android Studio

Open AndroidStudio as shown below

Copy and paste the three files into the libs directory

(Uniapp-releage.aar was imported when the dependency was added above)

Next add to android{} :

aaptOptions {additionalParameters '--auto-add-overlay' ignoreAssetsPattern "! .svn:! .git:.*:! CVS:! thumbs.db:! picasa.ini:! *.scc:*~"} Copies the codeCopy the code

Add to dependencies:

implementation fileTree(dir: 'libs', include: ['*.jar']) implementation fileTree(dir: 'libs', include: [' *. Aar ']) implementation "com. Android. Support: support - v4:28.0.0" implementation "Com. Android. Support: appcompat - v7:28.0.0" / * uniapp required library -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * / implementation 'com. Android. Support: recyclerview - v7:28.0.0' implementation 'com. Facebook. Fresco ": fresco" : 1.13.0' implementation "Com. Facebook. Fresco" : animated - GIF: 1.13.0 "/ * uniapp required library -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * / / / base needs to be over, Must add implementation 'com. Making. Bumptech. Glide: glide: 4.9.0' implementation 'com. Alibaba: fastjson: 1.1.46. Android' Implementation Project (Path: ': testPlugin ') // References the original plugin moduleCopy the code

Add:

repositories {  flatDir {   dirs 'libs'  }}
Copy the code

Go back to the top of the build.gradle(app) page and configure the app version number.

CompileSdkVersion is the compile version, buildToolsVersion is the build tool version, applicationId is the package name at creation time, minSdkVersion is the minimum compatible version, targetSdkVersion is the target version, If you are interested, you can search for the differences and connections between the three.

The value of versionCode needs to be set. Generally, the initial value is 1. When updating the version, the value of versionCode needs to be changed each time.

VersionName Indicates the major version number, the minor version number, and the revision number. 1.0.0 in the figure indicates the initial version number. You can query the rest information by yourself.

And then you synchronize it

Synchronization is complete

Copy the data folder you just moved to your custom folder to app> SRC > Main > Assets.

Go ahead and create the apps folder in the assets folder you just created. Copy the files (__UNI__179390F for me) that you just packaged locally into the Apps folder.

6.5 Customizing Base Configurations

In the app directory, open the manifest.json file in the apps folder under Assets and the dcloud_control. XML file in the data folder. Make sure that the ID in manifest.json is the same as the APPID in dcloud_control.xml.

And set debug and syncDebug on the root node to true

Condition configured

6.6 Name Configuration

> app> SRC >main>res>values > strings. XML file, open the XML file, and compare the name of the manifest. Change the name in strings. XML to “TestModule”.

(Note: the manifest.json file is in the

Assets >apps>__UNI__179390F> WWW

Click “Run” so far, both the real machine and the simulator can be used!

The end!

Author: anyRTC- Dong Muyu

Links: juejin. Cn/post / 690490…