当前位置:   article > 正文

UNI APP---Android端原生插件开发实战(一)_uni原生插件开发教程

uni原生插件开发教程

1.前言

最近一个项目要求我们的产品必须走网络隧道,并且提供了对应的SDK,很明显只能通过原生开发的方式才能实现这个流程,笔者没有做过原生开发,也没有学过java,所以也踩了不少坑啊,花了两天时间总算完成任务,今天系统的总结下步骤,由于是根据笔者的业务进行的开发,所以步骤上与细节之处与其他原生插件开发相关的文章可能会有些出入。还请带着辩证的心态阅读本文。

2.工具材料清单

工具/材料版本/版本名
HBuilder X3.1.4
Android Studio4.1.3
UNI-SDKAndroid-SDK@3.1.4.80686_20210305
Android Gradle Plugin Version4.1.1
Gradle Version6.5

3.SDK集成文档

这里是原生SDK指的是第三方厂家提供的SDK

3.1 介绍

  1. 安全隧道的aar使用的jar包guava-18.0.jar
  2. 安全隧道的aar引用的第三方工程
  1. implementation 'org.bouncycastle:bcprov-jdk15on:1.55'
  2. implementation 'org.apache.commons:commons-lang3:3.4'
  3. implementation 'org.slf4j:slf4j-api:1.7.21'
  4. 复制代码
  1. 安全隧道服务器的地址的配置,在资源文件中配置好安全隧道服务器的地址
  1. <string name="client_vpn_server_host">xxx.xxx.xxx.xx:xxxx</string>
  2. 复制代码
  1. 安全隧道在初始化后会自动获取白名单(异步动作),获取成功后会持久化到本地,因此,首次初始化安全隧道的时候可能相对会比较慢(因为有网络请求)

3.2 集成

安全隧道提供的是aar,必要的文档都已经打包在了aar中,仅需要在主工程中的build.gradle文件的

  1. dependencies{
  2. ...
  3. implementation(name: 'MXSocksCore-x.x.x.xxxxxxxx', ext: 'aar')
  4. ...
  5. }
  6. 复制代码

x.x.x.xxxxxxxx 为版本号,也可以自己修改,但要跟文件名对应 如果aar不在主工程的build.gradle文件中引用,需要在主文件的build.gradle文件的

  1. repositories {
  2. flatDir {
  3. dirs 'libs','子工程的libs的相对路径'
  4. }
  5. }
  6. 复制代码

中修改对应的相对路径

最后将aar放到工程的libs文件夹中

3.3 API

1、初始化隧道

  1. MXAppTunnel.getInstance().initAppTunnel(context, new AppTunnelInitComplete() {
  2. @Override
  3. public void appTunnelInitComplete() {
  4. //初始化完成
  5. }
  6. @Override
  7. public void appTunnelInitError(String msg) {
  8. //初始化失败
  9. }
  10. });
  11. 复制代码

隧道初始化必须在使用之前初始化完成,此动作是一个异步的动作,首次启动会获取白名单,获取成功后会存储到本地,之后的启动不会因为获取白名单而阻塞完成

2、安全隧道日志输出

  1. MXAppTunnel.getInstance().setLogPrintListener(new ILogPrint() {
  2. @Override
  3. public void log(String tag, String format, Object... objects) {
  4. }
  5. @Override
  6. public void log(String tag, String msg) {
  7. }
  8. @Override
  9. public void diagnosisLog(String msg) {
  10. }
  11. });
  12. 复制代码

3、安全隧道信息输出

  1. MXAppTunnel.getInstance().setProxyInfoCallBack(new IProxyInfoCallBack() {
  2. @Override
  3. public void sendProxyPort(int httpPort, int socksPort) {
  4. //安全隧道两个服务器端口
  5. //1、httpPort http本地代理服务器的端口
  6. //2、socksPort socks本地代理服务器的端口
  7. }
  8. @Override
  9. public void sendProxyWhiteList(List<String> list) {
  10. //list 安全隧道白名单
  11. }
  12. });
  13. 复制代码

3.4 安全隧道使用

安全隧道使用需要手动设置http和https请求的代理,仅提供两种网络请求的设置代理的方式,代理地址为xxx.x.x.x 端口在API第三条中有输出

1、HttpClient

  1. HttpHost httpHost = new HttpHost("xxx.x.x.x", xxxx);
  2. httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);
  3. 复制代码

2、HttpURLConnection

  1. SocketAddress sa = new InetSocketAddress("xxx.x.x.x", xxxx);
  2. //定义代理,此处的Proxy是源自java.net
  3. Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,sa);
  4. (HttpURLConnection) url.openConnection(proxy);
  5. 复制代码

3、HttpsURLConnection

  1. SocketAddress sa = new InetSocketAddress("xxx.x.x.x", xxxx);
  2. //定义代理,此处的Proxy是源自java.net
  3. Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,sa);
  4. (HttpsURLConnection) url.openConnection(proxy);
  5. 复制代码

注:实例代码中的端口xxxx都是假的,应该使用API第三条中输出的对应的端口

3.5 Demo

文件还提供了一个MainActivity.javaDemo

  1. package com.example.administrator.networkdemo.ui;
  2. import android.os.Bundle;
  3. import android.support.annotation.Nullable;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.util.Log;
  6. import android.view.View;
  7. import android.widget.Toast;
  8. import com.example.administrator.networkdemo.R;
  9. import com.minxing.vpn.MXAppTunnel;
  10. import com.minxing.vpn.callback.AppTunnelInitComplete;
  11. import com.minxing.vpn.callback.ILogPrint;
  12. import com.minxing.vpn.callback.IProxyInfoCallBack;
  13. import java.io.BufferedReader;
  14. import java.io.InputStream;
  15. import java.io.InputStreamReader;
  16. import java.net.HttpURLConnection;
  17. import java.net.InetSocketAddress;
  18. import java.net.Proxy;
  19. import java.net.SocketAddress;
  20. import java.net.URL;
  21. import java.util.List;
  22. public class MainActivity extends AppCompatActivity {
  23. private static final String TAG = "Test";
  24. private boolean isInit = false;
  25. private int httpPort1;
  26. @Override
  27. protected void onCreate(@Nullable Bundle savedInstanceState) {
  28. super.onCreate(savedInstanceState);
  29. setContentView(R.layout.activity_main);
  30. }
  31. public void initialize(View view) {
  32. MXAppTunnel.getInstance().setProxyInfoCallBack(new IProxyInfoCallBack() {
  33. @Override
  34. public void sendProxyPort(int httpPort, int socksPort) {
  35. //安全隧道两个服务器端⼝
  36. //1、httpPort http本地代理服务器的端⼝
  37. //2、socksPort socks本地代理服务器的端⼝
  38. httpPort1 = httpPort;
  39. Log.i(TAG, "httpPort: " + httpPort + " socksPort: " + socksPort);
  40. Toast.makeText(MainActivity.this, "httpPort: " + httpPort + " socksPort: " + socksPort, Toast.LENGTH_LONG).show();
  41. }
  42. @Override
  43. public void sendProxyWhiteList(List<String> list) {
  44. //list 安全隧道⽩名单
  45. StringBuilder stringBuilder = new StringBuilder();
  46. for (String s : list) {
  47. stringBuilder.append(s).append("\n");
  48. }
  49. Log.i(TAG, stringBuilder.toString());
  50. Toast.makeText(MainActivity.this, stringBuilder.toString(), Toast.LENGTH_LONG).show();
  51. }
  52. });
  53. MXAppTunnel.getInstance().initAppTunnel(MainActivity.this, new AppTunnelInitComplete() {
  54. @Override
  55. public void appTunnelInitComplete() {
  56. //初始化完成
  57. Log.i(TAG, "安全隧道初始化完成");
  58. Toast.makeText(MainActivity.this, "安全隧道初始化完成", Toast.LENGTH_SHORT).show();
  59. isInit = true;
  60. }
  61. @Override
  62. public void appTunnelInitError(String msg) {
  63. //初始化失败
  64. Log.i(TAG, "安全隧道初始化失败: " + msg);
  65. Toast.makeText(MainActivity.this, "安全隧道初始化失败: " + msg, Toast.LENGTH_SHORT).show();
  66. }
  67. });
  68. MXAppTunnel.getInstance().setLogPrintListener(new ILogPrint() {
  69. @Override
  70. public void log(String tag, String format, Object... objects) {
  71. Log.i(TAG, tag + " -1- format: " + format + " objects: " + objects);
  72. }
  73. @Override
  74. public void log(String tag, String msg) {
  75. Log.i(TAG, tag + " -2- msg: " + msg);
  76. }
  77. @Override
  78. public void diagnosisLog(String msg) {
  79. Log.i(TAG, " -3- msg: " + msg);
  80. }
  81. });
  82. }
  83. public void outputMXLog(View view) {
  84. if (!isInit) {
  85. Toast.makeText(MainActivity.this, "安全隧道未初始化", Toast.LENGTH_SHORT).show();
  86. return;
  87. }
  88. }
  89. public void outputMXInfo(View view) {
  90. if (!isInit) {
  91. Toast.makeText(MainActivity.this, "安全隧道未初始化", Toast.LENGTH_SHORT).show();
  92. return;
  93. }
  94. request(httpPort1);
  95. }
  96. private void request(final int port) {
  97. // OkHttpClient.Builder builder = new OkHttpClient.Builder();
  98. // builder.connectTimeout(1, TimeUnit.MINUTES);
  99. // Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", port));
  100. // builder.proxy(proxy);
  101. new Thread(new Runnable() {
  102. @Override
  103. public void run() {
  104. String url = "http://xx.xx.xx.xxxx:xxxx/xxxxx/xxxxxx?params1=value1&params2=value2&params3=value3";
  105. URL url1 = null;
  106. try {
  107. url1 = new URL(url);
  108. SocketAddress sa = new InetSocketAddress("127.0.0.1", port);
  109. //定义代理,此处的Proxy是源⾃java.net
  110. Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,sa);
  111. HttpURLConnection httpURLConnection =(HttpURLConnection) url1.openConnection(proxy);
  112. httpURLConnection.setRequestMethod("POST");
  113. //得到响应码
  114. int responseCode = httpURLConnection.getResponseCode();
  115. if(responseCode == HttpURLConnection.HTTP_OK){
  116. //得到响应流
  117. InputStream inputStream = httpURLConnection.getInputStream();
  118. //将响应流转换成字符串
  119. //String result = is2String(inputStream);//将流转换为字符串。
  120. //Log.d("kwwl","result============="+result);
  121. }
  122. InputStream inputStream = httpURLConnection.getInputStream();
  123. InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
  124. BufferedReader reader = new BufferedReader(inputStreamReader);
  125. String tempLine;
  126. StringBuilder resultBuffer = new StringBuilder();
  127. while ((tempLine = reader.readLine()) != null) {
  128. resultBuffer.append(tempLine);
  129. }
  130. Log.i(TAG, " -5- " + resultBuffer.toString());
  131. } catch (Exception e) {
  132. e.printStackTrace();
  133. Log.i(TAG, " -4- " + e.getMessage());
  134. }
  135. }
  136. }).start();
  137. // Request request = new Request.Builder().url(url).get().build();
  138. // Call call = builder.build().newCall(request);
  139. // call.enqueue(new Callback() {
  140. // @Override
  141. // public void onFailure(Call call, IOException e) {
  142. // final String s = e.getMessage();
  143. // Log.e(TAG, s);
  144. // runOnUiThread(new Runnable() {
  145. // @Override
  146. // public void run() {
  147. // Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
  148. // }
  149. // });
  150. // }
  151. //
  152. // @Override
  153. // public void onResponse(Call call, Response response) throws IOException {
  154. // final String s = response.body().string();
  155. // Log.e(TAG, s);
  156. // runOnUiThread(new Runnable() {
  157. // @Override
  158. // public void run() {
  159. // Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
  160. // }
  161. // });
  162. // }
  163. // });
  164. }
  165. }
  166. 复制代码

3.开发

3.1原生项目运行

为了开发原生插件,那么建立原生的项目工程这是必不可少的条件,为了方便开发这里直接使用了UNI-SDK文件夹中的UniPlugin-Hello-AS这个工程,直接拖入到Android Studio(以下简称AS)点击文件-新建-Import Project

选中UniPlugin-Hello-AS后点击确定,整个目录结构就出来了

现在点击运行按钮让示例项目跑起来。

3.2 插件开发

首先跟着Android原生插件开发教程,一步一步往下进行。 JDK安装和AS的安装就不写了,这些没啥大的问题,随便百度一个相关文章都能跑得起来

根据官方的注意,总体来说,我们在本地开发的时候注意配置gradletools.build:gradle 点击 文件-项目结构 查看我们的版本

安装官方的步骤,新建一个Module,在此之前我们先把项目结构转换Project类型的结构,然后点击 文件-新建-New Module

选择library

配置包名以及Module名称,点击完成(Finish)

按照官方的布置,新建完成了要去配置刚创建的Modulebuild.gradle信息,注意是Module的而不是app

新建完成可能会出现如下的错误信息

  1. Version 28 (intended for Android Pie and below) is the last version of the legacy support library, so we recommend that you migrate to AndroidX libraries when using Android Q and moving forward. The IDE can help with this: Refactor > Migrate to AndroidX... less... (Ctrl+F1)
  2. Inspection info:There are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion). Issue id: GradleCompatible
  3. 复制代码

具体的解决办法可以去百度,但是我发现这貌似仅仅是个警告,反正最后没有影响我的编译、运行和使用。

首先按照第三方SDK的配置说明,在资源文件中配置好安全隧道服务器的地址(注意是在main文件夹下) 参考如uniplugin_component等其他模块的配置格式新建res文件。

由于我们的网络隧道是做到Module插件模块中的,所以我们讲MXSDK放在Modulelibs中进行引用。

  1. plugins {
  2. id 'com.android.library'
  3. }
  4. android {
  5. compileSdkVersion 30
  6. buildToolsVersion "30.0.2"
  7. defaultConfig {
  8. minSdkVersion 16
  9. targetSdkVersion 30
  10. versionCode 1
  11. versionName "1.0"
  12. testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  13. consumerProguardFiles "consumer-rules.pro"
  14. }
  15. buildTypes {
  16. release {
  17. minifyEnabled false
  18. proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
  19. }
  20. }
  21. compileOptions {
  22. sourceCompatibility JavaVersion.VERSION_1_8
  23. targetCompatibility JavaVersion.VERSION_1_8
  24. }
  25. }
  26. //导入aar需要的配置
  27. repositories {
  28. flatDir {
  29. dirs 'libs' //指定arr的导入路径,默认是当前Module的libs目录
  30. }
  31. }
  32. dependencies {
  33. /**引入uniSDK必要的依赖开始**/
  34. //以com.等开头的是第三方的远程依赖库
  35. compileOnly 'com.android.support:recyclerview-v7:28.0.0'
  36. compileOnly 'com.android.support:support-v4:28.0.0'
  37. compileOnly 'com.android.support:appcompat-v7:28.0.0'
  38. compileOnly 'com.alibaba:fastjson:1.1.46.android'
  39. compileOnly fileTree(include: ['uniapp-v8-release.aar'], dir: '../app/libs') //这种引入方式 ../app/libs 指定了app目录下的模块的rarr文件
  40. /**引入uniSDK必要的依赖结束**/
  41. /**安全隧道的aar引用的第三方工程开始**/
  42. implementation 'org.bouncycastle:bcprov-jdk15on:1.55'
  43. implementation 'org.apache.commons:commons-lang3:3.4'
  44. implementation 'org.slf4j:slf4j-api:1.7.21'
  45. //引入MX本地arr文件(根据dirs 'libs'这个路径直接引用当前Module-libs目录)
  46. implementation(name: 'MXSocksCore-release_6.8.0_stable_socks_jar_160', ext: 'aar')
  47. /**安全隧道的aar引用的第三方工程结束**/
  48. }
  49. 复制代码

接入完毕,run一下,发现没抱错,下面开始定制化的开发。 新建一个类

按照官方的步骤这个类需要继承UniModule,按照DEMO里面的写法,具体如下

  1. package com.example.kysin;
  2. import android.util.Log;
  3. import android.view.View;
  4. import android.widget.Toast;
  5. import com.minxing.vpn.MXAppTunnel;
  6. import com.minxing.vpn.callback.AppTunnelInitComplete;
  7. import com.minxing.vpn.callback.ILogPrint;
  8. import com.minxing.vpn.callback.IProxyInfoCallBack;
  9. import java.util.List;
  10. import io.dcloud.feature.uniapp.common.UniModule;
  11. public class tunnel extends UniModule {
  12. private static final String TAG = "Test";
  13. private boolean isInit = false;
  14. private int httpPort1;
  15. public void initialize(View view) {
  16. MXAppTunnel.getInstance().setProxyInfoCallBack(new IProxyInfoCallBack() {
  17. @Override
  18. public void sendProxyPort(int httpPort, int socksPort) {
  19. //安全隧道两个服务器端⼝
  20. //1、httpPort http本地代理服务器的端⼝
  21. //2、socksPort socks本地代理服务器的端⼝
  22. httpPort1 = httpPort;
  23. Log.i(TAG, "httpPort: " + httpPort + " socksPort: " + socksPort);
  24. Toast.makeText(MainActivity.this, "httpPort: " + httpPort + " socksPort: " + socksPort, Toast.LENGTH_LONG).show();
  25. }
  26. @Override
  27. public void sendProxyWhiteList(List<String> list) {
  28. //list 安全隧道⽩名单
  29. StringBuilder stringBuilder = new StringBuilder();
  30. for (String s : list) {
  31. stringBuilder.append(s).append("\n");
  32. }
  33. Log.i(TAG, stringBuilder.toString());
  34. Toast.makeText(MainActivity.this, stringBuilder.toString(), Toast.LENGTH_LONG).show();
  35. }
  36. });
  37. MXAppTunnel.getInstance().initAppTunnel(MainActivity.this, new AppTunnelInitComplete() {
  38. @Override
  39. public void appTunnelInitComplete() {
  40. //初始化完成
  41. Log.i(TAG, "安全隧道初始化完成");
  42. Toast.makeText(MainActivity.this, "安全隧道初始化完成", Toast.LENGTH_SHORT).show();
  43. isInit = true;
  44. }
  45. @Override
  46. public void appTunnelInitError(String msg) {
  47. //初始化失败
  48. Log.i(TAG, "安全隧道初始化失败: " + msg);
  49. Toast.makeText(MainActivity.this, "安全隧道初始化失败: " + msg, Toast.LENGTH_SHORT).show();
  50. }
  51. });
  52. MXAppTunnel.getInstance().setLogPrintListener(new ILogPrint() {
  53. @Override
  54. public void log(String tag, String format, Object... objects) {
  55. Log.i(TAG, tag + " -1- format: " + format + " objects: " + objects);
  56. }
  57. @Override
  58. public void log(String tag, String msg) {
  59. Log.i(TAG, tag + " -2- msg: " + msg);
  60. }
  61. @Override
  62. public void diagnosisLog(String msg) {
  63. Log.i(TAG, " -3- msg: " + msg);
  64. }
  65. });
  66. }
  67. }
  68. 复制代码

这里IDE会提示“不能解决符号MainActivity

这里就涉及到了 "当前的上下文环境",按照传统的Activity方法,我们可以直接集成Activity然后写Activity.this或者通过getApplicationContext来得到执行的上下文。但是官方文档写到:

  • Activity的获取方式。通过mUniSDKInstance.getContext()强转Activity。建议先instanceof Activity判断一下再强转 所以这里我们改造下封装的方法,用mUniSDKInstance.getContext()代替Activity.this写法
  1. package com.example.kysin;
  2. import android.app.Activity;
  3. import android.util.Log;
  4. import android.view.View;
  5. import android.widget.Toast;
  6. import com.minxing.vpn.MXAppTunnel;
  7. import com.minxing.vpn.callback.AppTunnelInitComplete;
  8. import com.minxing.vpn.callback.ILogPrint;
  9. import com.minxing.vpn.callback.IProxyInfoCallBack;
  10. import java.util.List;
  11. import io.dcloud.feature.uniapp.annotation.UniJSMethod;
  12. import io.dcloud.feature.uniapp.common.UniModule;
  13. public class Tunnel extends UniModule {
  14. private static final String TAG = "Test";
  15. private boolean isInit = false;
  16. private int httpPort1;
  17. @UniJSMethod(uiThread = false)
  18. public void initialize() {
  19. Log.i(TAG, "11111");
  20. MXAppTunnel.getInstance().setProxyInfoCallBack(new IProxyInfoCallBack() {
  21. @Override
  22. public void sendProxyPort(int httpPort, int socksPort) {
  23. //安全隧道两个服务器端⼝
  24. //1、httpPort http本地代理服务器的端⼝
  25. //2、socksPort socks本地代理服务器的端⼝
  26. httpPort1 = httpPort;
  27. Log.i(TAG, "httpPort: " + httpPort + " socksPort: " + socksPort);
  28. Toast.makeText((Activity)mUniSDKInstance.getContext(), "httpPort: " + httpPort + " socksPort: " + socksPort, Toast.LENGTH_LONG).show();
  29. }
  30. @Override
  31. public void sendProxyWhiteList(List<String> list) {
  32. //list 安全隧道⽩名单
  33. StringBuilder stringBuilder = new StringBuilder();
  34. for (String s : list) {
  35. stringBuilder.append(s).append("\n");
  36. }
  37. Log.i(TAG, stringBuilder.toString());
  38. Toast.makeText((Activity)mUniSDKInstance.getContext(), stringBuilder.toString(), Toast.LENGTH_LONG).show();
  39. }
  40. });
  41. MXAppTunnel.getInstance().initAppTunnel((Activity)mUniSDKInstance.getContext(), new AppTunnelInitComplete() {
  42. @Override
  43. public void appTunnelInitComplete() {
  44. //初始化完成
  45. Log.i(TAG, "安全隧道初始化完成");
  46. Toast.makeText((Activity)mUniSDKInstance.getContext(), "安全隧道初始化完成", Toast.LENGTH_SHORT).show();
  47. isInit = true;
  48. }
  49. @Override
  50. public void appTunnelInitError(String msg) {
  51. //初始化失败
  52. Log.i(TAG, "安全隧道初始化失败: " + msg);
  53. Toast.makeText((Activity)mUniSDKInstance.getContext(), "安全隧道初始化失败: " + msg, Toast.LENGTH_SHORT).show();
  54. }
  55. });
  56. MXAppTunnel.getInstance().setLogPrintListener(new ILogPrint() {
  57. @Override
  58. public void log(String tag, String format, Object... objects) {
  59. Log.i(TAG, tag + " -1- format: " + format + " objects: " + objects);
  60. }
  61. @Override
  62. public void log(String tag, String msg) {
  63. Log.i(TAG, tag + " -2- msg: " + msg);
  64. }
  65. @Override
  66. public void diagnosisLog(String msg) {
  67. Log.i(TAG, " -3- msg: " + msg);
  68. }
  69. });
  70. }
  71. }
  72. 复制代码

3.3 在原生APP里进行插件测试

写完之后需要进行隧道初始化的测试 要在原生工程中实现这个Module的调用测试,需要进行下步骤:

  • 将原生插件在通过dcloud_uniplugins.json进行声明和Module引入
  • 新建一个自定义的UNI项目,并编写对应的调用方法

所以我们第一步是先去原生工程中进行插件的声明,按照官方文档描述: 在UniPlugin-Hello-AS工程下app-src-main-assets/dcloud_uniplugins.json文件。 在moudles节点下 添加你要注册的Module或 Component

  1. {
  2. "nativePlugins": [
  3. {
  4. "plugins": [
  5. {
  6. "type": "module",
  7. "name": "TestModule",
  8. "class": "io.dcloud.uniplugin.TestModule"
  9. }
  10. ]
  11. },
  12. {
  13. "plugins": [
  14. {
  15. "type": "component",
  16. "name": "myText",
  17. "class": "io.dcloud.uniplugin.TestText"
  18. }
  19. ]
  20. },
  21. {
  22. "hooksClass": "",
  23. "plugins": [
  24. {
  25. "type": "module",
  26. "name": "DCloud-RichAlert",
  27. "class": "uni.dcloud.io.uniplugin_richalert.RichAlertModule"
  28. }
  29. ]
  30. },
  31. {
  32. "plugins": [
  33. {
  34. "type": "module",
  35. "name": "test-Module", //这个名字可以随便取,只要和UNI项目中requireNativePlugin的相同就行
  36. "class": "com.example.kysin.Tunnel"
  37. }
  38. ]
  39. }
  40. ]
  41. }
  42. 复制代码

然后还要去app模块的build.gradle去添加新增的Moudle插件

  1. apply plugin: 'com.android.application'
  2. android {
  3. compileSdkVersion 29
  4. buildToolsVersion '28.0.3'
  5. defaultConfig {
  6. applicationId "com.HBuilder.UniPlugin"
  7. minSdkVersion 21
  8. targetSdkVersion 26 //建议此属性值设为21 io.dcloud.PandoraEntry 作为apk入口时 必须设置 targetSDKVersion>=21 沉浸式才生效
  9. versionCode 1
  10. versionName "1.0"
  11. multiDexEnabled true
  12. ndk {
  13. abiFilters 'x86','armeabi-v7a'
  14. }
  15. }
  16. buildTypes {
  17. release {
  18. zipAlignEnabled true
  19. minifyEnabled true
  20. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  21. }
  22. debug {
  23. zipAlignEnabled true
  24. minifyEnabled true
  25. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  26. }
  27. }
  28. //使用uniapp时,需复制下面代码
  29. /*代码开始*/
  30. aaptOptions {
  31. additionalParameters '--auto-add-overlay'
  32. //noCompress 'foo', 'bar'
  33. ignoreAssetsPattern "!.svn:!.git:.*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~"
  34. }
  35. /*代码结束*/
  36. }
  37. repositories {
  38. flatDir {
  39. dirs 'libs'
  40. }
  41. }
  42. dependencies {
  43. implementation fileTree(dir: 'libs', include: ['*.jar'])
  44. implementation fileTree(dir: 'libs', include: ['*.aar'])
  45. implementation "com.android.support:support-v4:28.0.0"
  46. implementation "com.android.support:appcompat-v7:28.0.0"
  47. /*uniapp所需库-----------------------开始*/
  48. implementation 'com.android.support:recyclerview-v7:28.0.0'
  49. implementation 'com.facebook.fresco:fresco:1.13.0'
  50. implementation "com.facebook.fresco:animated-gif:1.13.0"
  51. /*uniapp所需库-----------------------结束*/
  52. // 基座需要,必须添加
  53. implementation 'com.github.bumptech.glide:glide:4.9.0'
  54. implementation 'com.alibaba:fastjson:1.1.46.android'
  55. // 添加uni-app插件
  56. implementation project(':uniplugin_component')
  57. implementation project(':uniplugin_module')
  58. implementation project(':uniplugin_richalert')
  59. // 添加自定义插件
  60. implementation project(':testModule') //和你新建Module的文件夹名字保持一致
  61. }
  62. 复制代码

testModule模块Gradle.builde中本地的arr文件引入,我总结了以下几种情况

  1. //app工程libs如没有这个arr文件会报Coulad not resolve:MXSocksCore-release_6.8.0_stable_socks_jar_160:
  2. //app工程libs如没有这个arr文件会报Duplicate class com.google.common.annotations.Beta found in modules MXSocksCore-release_6.8.0_stable_socks_jar_160-runtime(:MXSocksCore-release_6.8.0_stable_socks_jar_160:) adn MXSocksCore-release_6.8.0_stable_socks_jar_160-runtime(MXSocksCore-release_6.8.0_stable_socks_jar_160.arr)
  3. //app无法编译运行
  4. implementation(name: 'MXSocksCore-release_6.8.0_stable_socks_jar_160', ext: 'aar')
  5. //情况同上
  6. api(name: 'MXSocksCore-release_6.8.0_stable_socks_jar_160', ext: 'aar')
  7. //app工程libs如没有这个arr文件会报警告,但是程序会正常启动,但是自定义的Module事件无法触发
  8. //Missing class:com.mingxing.vqn.callback.ApptunnellnitCompelet
  9. //Missing class: com.minxing.vpn.callback.IProxyInfoCallBack
  10. //Missing class: com.minxing.vpn.callback.ILogPrint
  11. //app工程libs有这个arr文件才能不报/Missing class,能正常运行
  12. compileOnly(name: 'MXSocksCore-release_6.8.0_stable_socks_jar_160', ext: 'aar')
  13. //app工程libs如没有这个arr文件也能正常运行
  14. //但是打包arr时报错:Direct local .aar file dependencies are not supported when building an AAR. The resulting AAR would be broken because the classes and Android resources from any local .aar file dependencies would not be packaged in the resulting AAR. Previous versions of the Android Gradle Plugin produce broken AARs in this case too (despite not throwing this error). The following direct local .aar file dependencies of the :testModule project caused this error: C:\Users\jnp\Desktop\jianshu\Android-SDK@3.1.4.80686_20210305\UniPlugin-Hello-AS\testModule\libs\MXSocksCore-release_6.8.0_stable_socks_jar_160.aar
  15. api fileTree(include: ['MXSocksCore-release_6.8.0_stable_socks_jar_160.aar'], dir: './libs')
  16. //app工程libs如没有这个arr文件也能正常运行
  17. //但是打包arr时报错:Direct local .aar file dependencies are not supported when building an AAR. The resulting AAR would be broken because the classes and Android resources from any local .aar file dependencies would not be packaged in the resulting AAR. Previous versions of the Android Gradle Plugin produce broken AARs in this case too (despite not throwing this error). The following direct local .aar file dependencies of the :testModule project caused this error: C:\Users\jnp\Desktop\jianshu\Android-SDK@3.1.4.80686_20210305\UniPlugin-Hello-AS\testModule\libs\MXSocksCore-release_6.8.0_stable_socks_jar_160.aar
  18. implementation fileTree(dir: 'libs', include: ['*.aar'])
  19. 复制代码

基于此本文只能选择compileOnly(name: 'MXSocksCore-release_6.8.0_stable_socks_jar_160', ext: 'aar')方式进行第三方arr插件引用,这里需要把第三方的arr包放1份到app模块的libs文件夹下

  1. plugins {
  2. id 'com.android.library'
  3. }
  4. android {
  5. compileSdkVersion 30
  6. buildToolsVersion "30.0.2"
  7. defaultConfig {
  8. minSdkVersion 16
  9. targetSdkVersion 30
  10. versionCode 1
  11. versionName "1.0"
  12. testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  13. consumerProguardFiles "consumer-rules.pro"
  14. }
  15. buildTypes {
  16. release {
  17. minifyEnabled false
  18. proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
  19. }
  20. }
  21. compileOptions {
  22. sourceCompatibility JavaVersion.VERSION_1_8
  23. targetCompatibility JavaVersion.VERSION_1_8
  24. }
  25. }
  26. //导入aar需要的配置
  27. repositories {
  28. flatDir {
  29. dirs 'libs' //指定arr的导入路径,默认是当前Module的libs目录
  30. }
  31. }
  32. dependencies {
  33. /**引入uniSDK必要的依赖开始**/
  34. //以com.等开头的是第三方的远程依赖库
  35. compileOnly 'com.android.support:recyclerview-v7:28.0.0'
  36. compileOnly 'com.android.support:support-v4:28.0.0'
  37. compileOnly 'com.android.support:appcompat-v7:28.0.0'
  38. compileOnly 'com.alibaba:fastjson:1.1.46.android'
  39. compileOnly fileTree(include: ['uniapp-v8-release.aar'], dir: '../app/libs') //这种引入方式 ../app/libs 指定了app目录下的模块的arr文件
  40. /**引入uniSDK必要的依赖结束**/
  41. /**安全隧道的aar引用的第三方工程开始**/
  42. implementation 'org.bouncycastle:bcprov-jdk15on:1.55'
  43. implementation 'org.apache.commons:commons-lang3:3.4'
  44. implementation 'org.slf4j:slf4j-api:1.7.21'
  45. //引入MX本地arr文件(根据dirs 'libs'这个路径直接引用当前Module-libs目录)
  46. compileOnly(name: 'MXSocksCore-release_6.8.0_stable_socks_jar_160', ext: 'aar')
  47. /**安全隧道的aar引用的第三方工程结束**/
  48. }
  49. 复制代码

然后去新建一个UNI项目,编写调用原生插件的代码

编写完成后,点击 发行-原生APP本地打包-生成本地打包APP资源

把原生工程中app-src-main-assets-apps目录下的__UNI__BCEC007这整个文件删除,然后把你打包完成以新的APPID命名的文件粘贴到刚刚删除干净的apps目录下这里以__UNI__911FD69为例子。

然后去app-src-main-assets-data-dcloud_control.xml中修改appid为你刚刚复制过来的那个appid

点击run,然后点击app首页的图标调用原生的方法 看看logcat的输入日志

以上可以看到能够正常的进行调用。插件测试成功

3.4 插件打包

插件打包第一步还是很简单的,点击IDE右侧的Gradle图标,找到uniPlugin-Hello-AS-testModule-Tasks-other-assembleRelease,双击assembleRelease

testModule-build-outputs-arr文件夹找到我们的testModule-release.arr 按照官方文档生成uni-app插件

打包之前一定要记得去manifest.json选择本地的原生插件,你会发现插件名就是之前package.json中的name字段。

打包的时候选择 运行-运行到手机或模拟器-制作自定义调试基座,等待打包完成点击运行本

 本文引自 稀土掘金网的扶不起的蝌蚪。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/287596
推荐阅读
相关标签
  

闽ICP备14008679号