日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

UNI APP---Android端原生插件开发实战(二)

發布時間:2023/12/15 Android 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 UNI APP---Android端原生插件开发实战(二) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.前言

最近一個項目要求我們的產品必須走網絡隧道,并且提供了對應的SDK,很明顯只能通過原生開發的方式才能實現這個流程,之前已經寫過一篇通過代理的方式進行數據請求,而這次Android端的方式是采用NBA的方式進行數據請求,下面開始進行原生插件的開發。

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

首先根據官方的gradel版本注意事項查看自己的gradle是否滿足要求

至于Android Gradle Plugin Version和Gradle Version在AS的File-Project Structure可以查看

3.SDK集成文檔

3.1介紹

3.1.1環境集成:

  • libsecure_portal.so庫只放入libs\armeabi文件夾下面,其他armeabi-v7a,armeabi64-v8等目錄請不要放置該so。

  • libsecure_portal.jar文件放入libs目錄下。

  • 配置build.gradle文件,增加以下配置

  • defaultConfig {ndk {abiFilters 'armeabi'} }sourceSets {main {jniLibs.srcDirs = ["libs"]} }復制代碼
  • 在AndroidMainfest.xml中加入權限
  • <service android:name="com.secure.sportal.sdk.NBA.SPNCService"android:permission="android.permission.BIND_NBA_SERVICE"><intent-filter><action android:name="android.net.NBAService" /></intent-filter> </service> 復制代碼

    以上4步完成后,環境配置完成。

    3.1.2 代碼集成

    1.配置NBA參數,連接NBA

    private static final int REQUEST_NC_CODE = 1234; public void connectNBA() {Properties params = new Properties();// 配置NBA服務器地址,端口params.setProperty(SPNBAClient.PARAM_NBA_HOST, "NBA公網地址 ");params.setProperty(SPNBAClient.PARAM_NBA_PORT, "NBA公網端口");// 認證服務器名稱,這里建議填空,默認使用第一個認證服務器params.setProperty(SPNBAClient.PARAM_AUTH_SERVER, "");// SSLNBA 登錄用戶名params.setProperty(SPNBAClient.PARAM_AUTH_USERNAME, "username");// SSLNBA 登錄密碼params.setProperty(SPNBAClient.PARAM_AUTH_PASSWORD, "password");// 可直接在UI主線程調用login()方法,SDK內部自動在非UI線程完成工作,// 并通過異步回調方式通知執行結果。login()會立即返回,不會阻塞。SPNBAClient.login(this, params, new SPNBAClient.OnNBALoginCallback() {@Overridepublic void onNBALoginMessage(int msgid, String msg) {//SSLNBA的登錄結果會回調該函數if (msgid == SPNBAClient.MSGID_LOGIN_SUCC) {// SSLNBA 登錄成功startTunnel(); // 啟動nc網卡} else if (msgid == SPNBAClient.MSGID_LOGIN_FAIL) {// SSLNBA 登錄失敗,打印出失敗信息Log.e(TAG, "連接服務器失敗 msgid is " + msgid + ", msg is " + msg);}}}); } 復制代碼

    2.NBA連接成功后啟動Android系統的NC網卡 注意:該函數第一次調用時會彈出系統授權框,詢問用戶是否允許建立虛擬網卡,這里必須要點"允許"才行。 如果第一次點了"拒絕"。則需要卸載APP,重啟手機后再重裝App,然后才會再次彈授權框給用戶選擇!!!

    private void startTunnel() {//判斷網關配置是否有下發NC業務,如沒有下發,則不需要建立nc網卡。if (SPNBAClient.needsNBATunnel()) {Intent intent = NBAService.prepare(getApplicationContext());if (intent != null) {// 用戶從未同意過NC權限,啟動對話框向用戶確認權限Log.e(TAG, "用戶未授權NC權限,啟動失敗");startActivityForResult(intent, REQUEST_NC_CODE);} else {// 用戶已確認權限可直接啟動NCLog.d(TAG, "startNBATunnel...");SPNBAClient.startNBATunnel(this, true, 0); //該函數最終會啟動nc網卡}} else {Log.e(TAG, "服務器未配置NC業務!");} } 復制代碼

    3.重寫onActivityResult

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {if (requestCode == REQUEST_NC_CODE) {log.d("result is " + resultCode);if (resultCode == RESULT_OK) {SPNBAClient.startNBATunnel(this, true, 0); //該函數最終會啟動nc網卡Log.d(TAG, "登錄成功,建立NC網卡成功");}} } 復制代碼

    4. 開發

    4.1原生項目運行

    為了開發原生插件,那么建立原生的項目工程這是必不可少的條件,為了方便開發這里直接使用了UNI-SDK文件夾中的UniPlugin-Hello-AS這個工程,直接拖入到Android Studio(以下簡稱AS)點擊文件-新建-Import Project,

    選中UniPlugin-Hello-AS后點擊確定,整個目錄結構就出來了

    現在點擊運行按鈕讓示例項目跑起來。

    4.2 插件開發

    首先跟著Android原生插件開發教程,一步一步往下進行。 按照官方的布置,新建完成了要去配置剛創建的Module的build.gradle信息,注意是Module的而不是app的 安裝官方的步驟,新建一個Module,在此之前我們先把項目結構轉換Project類型的結構,然后點擊 文件-新建-New Module

    選擇library

    配置包名以及Module名稱,點擊完成(Finish)

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

    新建完成可能會出現如下的錯誤信息

    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) 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 復制代碼

    具體的解決辦法可以去百度,但是我發現這貌似僅僅是個警告,反正最后沒有影響我的編譯、運行和使用。

    4.2.1 SDK配置

    按照第三方SDK的配置說明

  • libsecure_portal.so庫只放入libs\armeabi文件夾下面,其他armeabi-v7a,armeabi64-v8等目錄請不要放置該so。

  • libsecure_portal.jar文件放入libs目錄下。

  • 配置build.gradle文件,增加以下配置
  • defaultConfig {ndk {abiFilters 'armeabi'} }sourceSets {main {jniLibs.srcDirs = ["libs"]} }復制代碼

    根據上面的配置描述,對NBATunnel module的build.gradle進行修改

    //修改前 plugins {id 'com.android.library' }android {compileSdkVersion 30buildToolsVersion "30.0.3"defaultConfig {minSdkVersion 16targetSdkVersion 30versionCode 1versionName "1.0"testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"consumerProguardFiles "consumer-rules.pro"}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'}}compileOptions {sourceCompatibility JavaVersion.VERSION_1_8targetCompatibility JavaVersion.VERSION_1_8} }dependencies {implementation 'com.android.support:appcompat-v7:28.0.0'testImplementation 'junit:junit:4.+'androidTestImplementation 'com.android.support.test:runner:1.0.2'androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } 復制代碼

    修改后

    plugins {id 'com.android.library' }android {compileSdkVersion 30defaultConfig {minSdkVersion 16targetSdkVersion 30versionCode 1versionName "1.0"ndk {abiFilters "armeabi-v7a", "x86" //this 貨}testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"consumerProguardFiles "consumer-rules.pro"}sourceSets {main {//在 AS 中它會自動去加載 jniLibs 目錄中的 *.so 文件(工程目錄而不是在module目錄)。如果你放在了其它任何目錄,你必須要告訴它你將這些文件放在那里了(重定向)。// 這里我寫 `libs`,它就會去當前module的 `libs` 目錄中找,你也可以放在其它任何目錄中。jniLibs.srcDirs = ["libs"]}}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'}}compileOptions {sourceCompatibility JavaVersion.VERSION_1_8targetCompatibility JavaVersion.VERSION_1_8} }dependencies {/**引入uniSDK必要的依賴開始**///以com.等開頭的是第三方的遠程依賴庫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'compileOnly 'com.alibaba:fastjson:1.1.46.android'compileOnly fileTree(include: ['uniapp-v8-release.aar'], dir: '../app/libs') //這種引入方式 ../app/libs 指定了app目錄下的模塊的rarr文件/**引入uniSDK必要的依賴結束**///結合上面的 jniLibs.srcDirs = ["libs"]implementation files('libs/libsecure_portal.jar') } 復制代碼

    對于NBATunnel模塊Gradle.builde中本地的arr文件引入,我總結了以下幾種情況

    //可以正常的運行,但是打包會出錯 //implementation files('libs/libsecure_portal.jar') //無法編譯Could not find method filetree() for arguments [{dir=libs, include=[*.jar]}] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. //implementation filetree(dir: 'libs', include: ['*.jar']) //Could not resolve all files for configuration ':app:debugRuntimeClasspath'. //implementation(name: 'libsecure_portal.jar', ext: 'jar') //可以通過編譯,但是運行的時候會提示找不到類里面的方法 //compileOnly files('libs/libsecure_portal.jar') //可以通過編譯和運行 //compile fileTree(dir: 'libs', include: ['*.jar']) 環境配置完畢厚,下面進行業務代碼的開發 復制代碼
  • 在AndroidMainfest.xml中加入權限
  • <service android:name="com.secure.sportal.sdk.NBA.SPNCService"android:permission="android.permission.BIND_NBA_SERVICE"><intent-filter><action android:name="android.net.NBAService" /></intent-filter> </service> 復制代碼

    環境配置完成,下面進行業務代碼的開發

    4.2.2 原生代碼業務實現

    按照官方的步驟這個類需要繼承UniModule,按照DEMO里面的寫法,具體如下

    package com.example.NBAmodule;import android.app.Activity; import android.content.Intent; import android.net.NBAService; import android.util.Log;import com.alibaba.fastjson.JSONObject; import com.secure.sportal.sdk.SPNBAClient;import java.util.Properties;import io.dcloud.feature.uniapp.annotation.UniJSMethod; import io.dcloud.feature.uniapp.bridge.UniJSCallback; import io.dcloud.feature.uniapp.common.UniModule;import static android.app.Activity.RESULT_OK;public class NBATunnel extends UniModule {private static final int REQUEST_NC_CODE = 1234;String TAG = "結果";private UniJSCallback callback;@UniJSMethod(uiThread = false)public void connectNBA(JSONObject options, UniJSCallback callback1) {callback = callback1;//獲取JS層傳遞過來的網關賬號和密碼String username = options.getString("NBAUsername");String password = options.getString("NBAPassword");Log.i(TAG, username);Log.i(TAG, password);Properties params = new Properties();params.setProperty(SPNBAClient.PARAM_NBA_HOST, "xxx.xxx.xxx.xx");params.setProperty(SPNBAClient.PARAM_NBA_PORT, "xxx");params.setProperty(SPNBAClient.PARAM_AUTH_SERVER, "");params.setProperty(SPNBAClient.PARAM_AUTH_USERNAME, username);params.setProperty(SPNBAClient.PARAM_AUTH_PASSWORD, password);// 可直接在UI主線程調用login()方法,SDK內部自動在非UI線程完成工作,// 并通過異步回調方式通知執行結果。login()會立即返回,不會阻塞。SPNBAClient.login(mUniSDKInstance.getContext(), params, new SPNBAClient.OnNBALoginCallback() {@Overridepublic void onNBALoginMessage(int msgid, String msg) {//SSLNBA的登錄結果會回調該函數if ( msgid==SPNBAClient.MSGID_LOGIN_SUCC ){Log.i("msgid", String.valueOf(msgid));Log.i("msgid", msg);// SSLNBA 登錄成功startTunnel(); // 啟動nc網卡}else if ( msgid==SPNBAClient.MSGID_LOGIN_FAIL ){// SSLNBA 登錄失敗,打印出失敗信息callback.invoke("網關登錄失敗:"+msg);}}});}@UniJSMethod(uiThread = false)private void startTunnel() {//判斷網關配置是否有下發NC業務,如沒有下發,則不需要建立nc網卡。if (SPNBAClient.needsNBATunnel()){Intent intent = NBAService.prepare(mUniSDKInstance.getContext());if (intent != null){// 用戶從未同意過NC權限,啟動對話框向用戶確認權限 // Log.e(TAG, "用戶未授權NC權限,啟動失敗");callback.invoke("請求權限");((Activity)mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_NC_CODE);}else{// 用戶已確認權限可直接啟動NCLog.d(TAG, "startNBATunnel...");SPNBAClient.startNBATunnel(mUniSDKInstance.getContext(), true, 0);//該函數最終會啟動nc網卡callback.invoke("網關登錄成功");}}else{callback.invoke("服務器未配置NC業務");}}@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);Log.d("結果","result is " + resultCode+requestCode+data);if (requestCode == REQUEST_NC_CODE){callback.invoke("權限許可成功");if (resultCode == RESULT_OK){SPNBAClient.startNBATunnel(mUniSDKInstance.getContext(), true, 0);//該函數最終會啟動nc網卡callback.invoke("登錄成功,建立NC網卡成功");}}else{callback.invoke("權限許可失敗");}} } 復制代碼

    4.2.3 UNI代碼編寫

    新建一個UNI項目,編寫調用原生插件的代碼

    <template><view><!--狀態欄 --><view class="status_bar"></view><view class="login"><view class="content"><!-- 頭部logo --><view class="header"><image src="@/static/images/logo.png"></image></view><text class="title"></text><!-- 主體表單 --><view class="main"><wInput v-model="account" type="text" placeholder="賬號" :focus="isFocus" :disabled="disabled"></wInput><wInput v-model="password" type="password" placeholder="密碼" :disabled="disabled"></wInput></view><wButton class="wbutton" text="登 錄" :rotate="isRotate" @click="startLogin"></wButton></view><yomol-upgrade :type="upgradeType" :url="upgradeUrl" title="發現新版本" :content="upgradeContent"ref="yomolUpgrade"></yomol-upgrade><!-- 網關modal --><tui-modal :show="modal" :custom="true" fadeIn ><view class="tui-modal-custom"><view class="tui-prompt-title">NBA賬號</view><input class="tui-modal-input" v-model="NBAUsername" /><view class="tui-prompt-title">NBA密碼</view><input class="tui-modal-input password" v-model="NBAPassword" /><tui-button height="72rpx" :size="28" shape="circle" @click="requestNBA">提交</tui-button></view></tui-modal></view></view> </template><script>let tunnelif (uni.getSystemInfoSync().platform == "android")tunnel = uni.requireNativePlugin('NBATunnel')if (uni.getSystemInfoSync().platform == "ios")tunnel = uni.requireNativePlugin("NBATunnel-NBATunnel")import wInput from "@/components/watch-login/watch-input.vue"; import wButton from "@/components/watch-login/watch-button.vue"; import tuiModal from '@/components/tui-modal/tui-modal.vue';import { DbHelper } from "@/js/db.js";export default {data() {return {account: "",password: "",isRotate: false, //是否加載旋轉isFocus: false, // 是否聚焦disabled: false,upgradeType: "pkg", //pkg 整包 wgt 升級包upgradeContent: "", //更新內容upgradeUrl: "", //更新地址NBAUsername:'',NBAPassword:'',modal:false,};},components: {wInput,wButton,},async mounted() {await DbHelper.init();this.isLogin();},methods: {async isLogin() {if (uni.getSystemInfoSync().platform == "android"){uni.showLoading({mask:true})//無本地NBA數據if(!uni.getStorageSync('NBAInfo')){uni.hideLoading()let [,res] = await uni.showModal({content: '即將發起NBA權限請求,請點擊確認,若在此過程中退出應用或者拒絕了權限,需要重裝本應用才能重新發起NBA權限請求!',showCancel:false,});this.modal = true}else//有本地NBA數據,說明之前已經建立了網卡{let NBAInfo = uni.getStorageSync('NBAInfo')this.NBAUsername = NBAInfo.NBAUsernamethis.NBAPassword = NBAInfo.NBAPassworduni.hideLoading()await this.requestNBA()}}if (uni.getSystemInfoSync().platform == "ios") {uni.showLoading({mask:true})//無本地NBA數據if(!uni.getStorageSync('NBAInfo')){uni.hideLoading()let [,res] = await uni.showModal({content: '請輸入正確的NBA賬號密碼才能后續登錄!',showCancel:false,});this.modal = true}else//有本地NBA數據,說明之前已經建立了網卡{let NBAInfo = uni.getStorageSync('NBAInfo')this.NBAUsername = NBAInfo.NBAUsernamethis.NBAPassword = NBAInfo.NBAPassworduni.hideLoading()await this.requestNBA()}}},/*** @description 連接NBA服務器*/async requestNBA(){return new Promise((resolve,rejcet) => {uni.showLoading({title: 'NBA連接中...',mask: true});if (!this.NBAUsername)return uni.showToast({title: "NBA賬號不能為空!",icon: "none"}); // 顯示提示框if (!this.NBAPassword)return uni.showToast({title: "NBA密碼不能為空!",icon: "none"});if (uni.getSystemInfoSync().platform == "android") {tunnel.connectNBA({NBAUsername:this.NBAUsername,NBAPassword:this.NBAPassword},async res=>{this.modal = falseuni.hideLoading()if(res == '網關登錄成功' || res == '請求權限'){let NBAInfo = {NBAUsername:this.NBAUsername,NBAPassword:this.NBAPassword}uni.setStorageSync('NBAInfo',NBAInfo);let { account,password } = uni.getStorageSync("userInfo"); // 從本地緩存中同步獲取指定 key 對應的內容。if (!account) return; // 本地沒有用戶信息 直接返回(停留在登錄頁面)this.isFocus = false;this.isRotate = true;this.disabled = true;this.account = account;this.password = password;setTimeout(()=>{this.getUpdate()},1000)}else {if(/02000405/.test(res)){await uni.showModal({content:`NBA賬號或者密碼錯誤,請重新輸入` ,showCancel:false,});this.NBAUsername = ''this.NBAPassword = ''uni.removeStorageSync('NBAInfo');this.modal = true}else{uni.showModal({content:res,showCancel:false}); }rejcet(res)}})}if (uni.getSystemInfoSync().platform == "ios") {let NBAInfo = {NBAUsername:this.NBAUsername,NBAPassword:this.NBAPassword}tunnel.connectNBA(NBAInfo,async res=>{console.log(res); this.modal = falseuni.hideLoading()if(res == '網關登錄成功' || res == '請求權限'){uni.setStorageSync('NBAInfo',NBAInfo);let { account,password } = uni.getStorageSync("userInfo"); // 從本地緩存中同步獲取指定 key 對應的內容。if (!account) return; // 本地沒有用戶信息 直接返回(停留在登錄頁面)this.isFocus = false;this.isRotate = true;this.disabled = true;this.account = account;this.password = password;setTimeout(()=>{this.getUpdate()},1000)}else {if(/用戶名或密碼錯誤/.test(res)){await uni.showModal({content:`NBA賬號或者密碼錯誤,請重新輸入` ,showCancel:false,});this.NBAUsername = ''this.NBAPassword = ''uni.removeStorageSync('NBAInfo');this.modal = true}else{uni.showModal({title:"NBA登錄失敗",content:res,showCancel:false}); }rejcet(res)}})}})},// 檢查網絡狀態,并進一步檢查APP更新情況(有網條件)async getUpdate() {let [, netWork] = await uni.getNetworkType()if (netWork.networkType == "2g" || netWork.networkType == "none") {if (uni.getStorageSync("userInfo"))uni.reLaunch({url: "/pages/home/home"}); } else{console.log(plus.runtime.appid);plus.runtime.getProperty(plus.runtime.appid, async widgetInfo => {let option = {params:{appid: 'com.sklgp.warningSystem.ddh',version: plus.runtime.version,imei: plus.device.imei,}}if (uni.getSystemInfoSync().platform == "android")var {data: res} = await this.$http.get('/api/basedata/GetAppUpdateMsg',option)if (uni.getSystemInfoSync().platform == "ios")var {data: res} = await this.$http.getProxy('/api/basedata/GetAppUpdateMsg',option)if (res.data) {if (uni.getSystemInfoSync().platform == "android") {this.upgradeUrl = res.data.DownLoadURL;this.upgradeContent = res.data.Describe || "1.性能優化\n2.修復部分錯誤"this.$refs.yomolUpgrade.show();}if (uni.getSystemInfoSync().platform == "ios"){await uni.showModal({content: '有新的版本發布,請前往應用商店更新!',showCancel:false});}} else uni.reLaunch({url: "/pages/home/home"})});}},async startLogin(e) {if (this.isRotate) return;if (!this.account)return uni.showToast({title: "賬號不能為空!",icon: "none"}); // 顯示提示框if (!this.password)return uni.showToast({title: "密碼不能為空!",icon: "none"});this.isRotate = true; this.disabled = true; let res;if (uni.getSystemInfoSync().platform == "android"){try {let data = await this.$http.post("/api/security/token", {username: this.account,password: this.password,});res = data.data;} catch (e) {this.isRotate = false;this.disabled = false;return;}let {data: res2} = await this.$http.get("/api/account/GetUserInfo",{custom: { auth: false },header: { token: res.token }});let userInfo = {account: this.account,password: this.password,token: res.token};for (let key in res2.data) {userInfo[key] = res2.data[key];}uni.setStorageSync("userInfo", userInfo); await this.getUpdate()this.isRotate = false;}if (uni.getSystemInfoSync().platform == "ios") {tunnel.post({url:`${this.$http.config.baseURL}/api/security/token?username=${this.account}&password=${this.password}`,},callBack=>{callBack = JSON.parse(callBack)console.log(callBack);//存儲tokenif(callBack.status != 0){uni.showToast({title: callBack.msg,icon: 'none'});this.isRotate = false;this.disabled = false;return}tunnel.get({url:`${this.$http.config.baseURL}/api/account/GetUserInfo`,token:callBack.token},callBack2=>{callBack2 = JSON.parse(callBack2)console.log(callBack2);let userInfo = {account: this.account,password: this.password,token: callBack.token};for (let key in callBack2.data) {userInfo[key] = callBack2.data[key];}console.log(userInfo);uni.setStorageSync("userInfo", userInfo); this.getUpdate()}) })}},},}; </script> 復制代碼

    編寫完成后,右鍵UNI項目: 發行-原生APP本地打包-生成本地打包APP資源

    把原生工程中app/src/main/assets/apps目錄下的__UNI__BCEC007這整個文件刪除,然后把你打包完成以新的APPID命名的文件粘貼到剛剛刪除干凈的apps目錄下這里以__UNI__BAC0197為例子。

    然后去app-src-main-assets-data-dcloud_control.xml中修改appid為你剛剛復制過來的那個appid

    4.2.4 在原生APP里進行插件測試

    寫完之后需要進行隧道初始化的測試 要在原生工程中實現這個Module的調用測試,需要進行下步驟:

    • 將原生插件在通過dcloud_uniplugins.json進行聲明和Module引入
    • 新建一個自定義的UNI項目,并編寫對應的調用方法

    所以我們第一步是先去原生工程中進行插件的聲明,按照官方文檔描述: 在UniPlugin-Hello-AS工程下app-src-main-assets/dcloud_uniplugins.json文件。 在moudles節點下 添加你要注冊的Module或?Component

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

    apply plugin: 'com.android.application'android {compileSdkVersion 29buildToolsVersion '28.0.3'defaultConfig {applicationId "com.HBuilder.UniPlugin"minSdkVersion 21targetSdkVersion 21 //建議此屬性值設為21 io.dcloud.PandoraEntry 作為apk入口時 必須設置 targetSDKVersion>=21 沉浸式才生效versionCode 1versionName "1.0"multiDexEnabled truendk {abiFilters "armeabi-v7a", "x86" //this 貨}}buildTypes {release {zipAlignEnabled trueminifyEnabled trueproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}debug {zipAlignEnabled trueminifyEnabled trueproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}//使用uniapp時,需復制下面代碼/*代碼開始*/aaptOptions {additionalParameters '--auto-add-overlay'//noCompress 'foo', 'bar'ignoreAssetsPattern "!.svn:!.git:.*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~"}/*代碼結束*/ } repositories {flatDir {dirs 'libs'} } 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所需庫-----------------------開始*/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所需庫-----------------------結束*/// 基座需要,必須添加implementation 'com.github.bumptech.glide:glide:4.9.0'implementation 'com.alibaba:fastjson:1.1.46.android'// 添加uni-app插件 // implementation project(':uniplugin_component') // implementation project(':uniplugin_module') // implementation project(':uniplugin_richalert')implementation project(':NBAModule') } 復制代碼

    配置完成后點擊run,然后點擊app首頁的圖標調用原生的方法

    以上可以看到能夠正常的進行調用。插件測試成功

    5 插件打包

    插件打包第一步還是很簡單的,點擊IDE右側的Gradle圖標,找到uniPlugin-Hello-AS/testModule/Tasks/NBATunnel/other/assembleRelease,雙擊assembleRelease

    在NBATunnel/build/outputs/arr文件夾找到我們的NBATunnel-release.arr?按照插件編寫命名規范生成uni-app插件的package.json

    具體代碼

    {"name": "原生插件","id": "NBATunnel","version": "1.0","description": "原生插件","_dp_type":"nativeplugin","_dp_nativeplugin":{"android": {"plugins": [{"type": "module","name": "NBATunnel","class": "com.example.NBAmodule.NBATunnel"}],"hooksClass": "","integrateType": "aar","dependencies": [],"compileOptions": { "sourceCompatibility": "1.8","targetCompatibility": "1.8"},"abis": ["armeabi-v7a","x86"],"minSdkVersion": "16","useAndroidX": false, "permissions": [],"parameters": {}}} } 復制代碼

    打包之前一定要記得去manifest.json選擇本地的原生插件,你會發現插件名就是之前package.json中的name字段。

    打包的時候選擇 運行-運行到手機或模擬器-制作自定義調試基座,等待打包完成點擊運行即可,如果沒有問題就可以打正式包了

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

    總結

    以上是生活随笔為你收集整理的UNI APP---Android端原生插件开发实战(二)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。