轉(zhuǎn)自http://www.lxweimin.com/p/89afba199d69
uniapp原生sdk插件開發(fā)(uniapp調(diào)用原生代碼)
eliteTyc關注
12020.05.17 01:47:10字數(shù) 1,394閱讀 25,832
先貼上原生sdk插件開發(fā)官網(wǎng):https://nativesupport.dcloud.net.cn/NativePlugin/course/android
原生sdk開發(fā),目前包含兩種:
1.Module擴展開發(fā),非UI型擴展,即uniapp調(diào)用原生代碼的方法
2.Component擴展插件開發(fā),UI型擴展,原生控件的擴展調(diào)用
現(xiàn)在開始,公共方法
第一步:下載uniSDK地址(https://nativesupport.dcloud.net.cn/AppDocs/download/android)
image.png
我這里選擇穩(wěn)定版本進行下載,下載后解壓后目錄內(nèi)容如下,主要要使用的是箭頭標注的項目
image.png
第二步:創(chuàng)建原生項目,已有原生項目可以跳過(注意需要配置的東西是否配置好)
image.png
注意:uni原生sdk插件目前暫不支持kotlin,所以這里選擇java
第三步:創(chuàng)建為library的module,我這里取名elitetyc_plugin
image.png
第四步,拷貝aar包到lib目錄下
aar包在sdk中UniPlugin-Hello-AS/app/libs目錄下
image.png
第五步:配置module的build.gradle文件
apply plugin: 'com.android.library'android {? ? compileSdkVersion 29? ? buildToolsVersion "29.0.3"? ? defaultConfig {? ? ? ? minSdkVersion 19? ? ? ? targetSdkVersion 29? ? ? ? versionCode 1? ? ? ? versionName "1.0"? ? ? ? testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"? ? ? ? consumerProguardFiles 'consumer-rules.pro'? ? }? ? buildTypes {? ? ? ? release {? ? ? ? ? ? minifyEnabled false? ? ? ? ? ? proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'? ? ? ? }? ? }}//導入aar需要的配置repositories {? ? flatDir {? ? ? ? dirs 'libs'? ? }}dependencies {? ? implementation 'androidx.appcompat:appcompat:1.1.0'? ? testImplementation 'junit:junit:4.12'? ? androidTestImplementation 'androidx.test.ext:junit:1.1.1'? ? androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'? ? //必須添加的依賴? ? //noinspection GradleCompatible? ? compileOnly 'com.android.support:recyclerview-v7:27.1.0'? ? //noinspection GradleCompatible? ? compileOnly 'com.android.support:support-v4:27.1.0'? ? //noinspection GradleCompatible? ? compileOnly 'com.android.support:appcompat-v7:27.1.0'? ? compileOnly 'com.alibaba:fastjson:1.1.46.android'? ? implementation fileTree(dir: '../app/libs', include: ['*.aar', '*.jar'], exclude: [])}
第六步,將插件module作為依賴添加到主項目中
默認新建的module沒有依賴進主項目,需要在app的build.gradle中的依賴中加入以下代碼(注意換成自己的插件模塊名稱)
implementation project(path: ':elitetyc_plugin')
最后加上app的build.gradle文件
apply plugin: 'com.android.application'android {? ? compileSdkVersion 29? ? buildToolsVersion "29.0.3"? ? defaultConfig {? ? ? ? applicationId "com.elitetyc.uninativetest"? ? ? ? minSdkVersion 19? ? ? ? targetSdkVersion 29? ? ? ? versionCode 1? ? ? ? versionName "1.0"? ? ? ? testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"? ? }? ? buildTypes {? ? ? ? release {? ? ? ? ? ? minifyEnabled false? ? ? ? ? ? proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'? ? ? ? }? ? }? ? //使用uniapp時,需復制下面代碼? ? /*代碼開始*/? ? aaptOptions {? ? ? ? additionalParameters '--auto-add-overlay'? ? ? ? //noCompress 'foo', 'bar'? ? ? ? ignoreAssetsPattern "!.svn:!.git:.*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~"? ? }? ? /*代碼結(jié)束*/}//導入aar需要的配置repositories {? ? flatDir {? ? ? ? dirs 'libs'? ? }}dependencies {? ? implementation fileTree(dir: 'libs', include: ['*.jar','*.aar'])? ? implementation 'androidx.appcompat:appcompat:1.1.0'? ? implementation 'androidx.constraintlayout:constraintlayout:1.1.3'? ? testImplementation 'junit:junit:4.12'? ? androidTestImplementation 'androidx.test.ext:junit:1.1.1'? ? androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'? ? /*uniapp所需庫-----------------------開始*/? ? implementation 'com.android.support:recyclerview-v7:27.1.0'? ? implementation 'com.facebook.fresco:fresco:1.13.0'? ? implementation "com.facebook.fresco:animated-gif:1.13.0"? ? /*uniapp所需庫-----------------------結(jié)束*/? ? // 基座需要,必須添加? ? implementation 'com.github.bumptech.glide:glide:4.9.0'? ? implementation 'com.alibaba:fastjson:1.1.46.android'? ? implementation project(path: ':elitetyc_plugin')}
注釋的地方都是重點,否則最后運行起來會白屏!!!
第七步:加入混淆module的proguard-rules.pro文件
#module擴展的混淆-keeppublicclass*extendscom.taobao.weex.common.WXModule{*;}#component擴展混淆-keeppublicclass*extendscom.taobao.weex.ui.component.WXComponent{*;}
到這里module擴展插件和component擴展插件的公共配置就好了,接下來,分開講如何進行擴展
module擴展插件
在模塊中新建一個類,module擴展需要繼承WxModule如下
publicclassTestModulePluginextendsWXModule{privatefinalStringTAG="elitetyc===>>";@JSMethod(uiThread=true)publicvoidcalcNum(JSONObjectoptions,JSCallbackcallback){Log.e(TAG,"調(diào)用了call方法,兩個數(shù)字相加");Integernum1=options.getInteger("num1");Integernum2=options.getInteger("num2");Integerres=num1+num2;JSONObjectjsonObject=newJSONObject();jsonObject.put("res",res);callback.invoke(jsonObject);}@JSMethod(uiThread=false)publicvoidsleepCalcNum(JSONObjectoptions,JSCallbackcallback){Log.e(TAG,"調(diào)用了sleepCalcNum方法,睡眠3秒,兩個數(shù)字相加");try{Thread.sleep(3000);}catch(InterruptedExceptione){e.printStackTrace();}Integernum1=options.getInteger("num1");Integernum2=options.getInteger("num2");Integerres=num1+num2;JSONObjectjsonObject=newJSONObject();jsonObject.put("res",res);callback.invoke(jsonObject);}}
@JSMethod():表名這是一個插件方法,可以被uniapp調(diào)用,uiThread = true 或者false,表名這個方法是否執(zhí)行在Ui線程,一般耗時操作在非UI線程,非耗時任務在UI線程,這里寫了兩個方法,第二個方法執(zhí)行耗時任務(隨眠3秒,在進行計算)
方法名:方法名很重要,在uniapp中調(diào)用時會用到這個方法名
參數(shù):第一個參數(shù):JSONObject options,這是uniapp調(diào)用時傳過來的參數(shù),可以通過k-v方式獲取,第二個參數(shù),回調(diào)函數(shù)對象,調(diào)用函數(shù)的invoke方法可以將結(jié)果返回。
注意:到這里module擴展的方法就算寫好了,這里記下這個類的全類名com.elitetyc.elitetyc_plugin.TestModulePlugin,因為后面還需要注冊,講完component擴展后一起注冊。
component擴展插件
新建一個類如下,component擴展需要繼承,WXComponent,泛型為需要擴展的原生控件
publicclassTestComponentPluginextendsWXComponent<TextView>{publicTestComponentPlugin(WXSDKInstanceinstance,WXVContainerparent,BasicComponentDatabasicComponentData){super(instance,parent,basicComponentData);}/**
? ? *構(gòu)建component的view時會回調(diào)此函數(shù)
? ? * @param context
? ? * @return
? ? */@OverrideprotectedTextViewinitComponentHostView(@NonNullContextcontext){TextViewtextView=newTextView(context);textView.setTextColor(Color.RED);textView.setTextSize(30);returntextView;}/**
? ? * 配置屬性名
? ? * @param telNumber
? ? */@WXComponentProp(name="tel")publicvoidsetTel(StringtelNumber){getHostView().setText("tyc聯(lián)系電話: "+telNumber);}/**
? ? * 清除聯(lián)系電話
? ? */@JSMethodpublicvoidclearTel(){getHostView().setText("tyc聯(lián)系電話: 電話已清除");}/**
? ? * 原生調(diào)用uniapp中的方法
? ? */@JSMethodpublicvoidshowTel(){Stringstr=getHostView().getText().toString();//原生觸發(fā)fireEvent 自定義事件onTelMap<String,Object>params=newHashMap<>();Map<String,Object>number=newHashMap<>();number.put("tel","我是android返回的:"+str);//目前uni限制 參數(shù)需要放入到"detail"中 否則會被清理params.put("detail",number);fireEvent("onTel",params);}}
從上到下
initComponentHostView:這個方法是在uniapp中使用這個擴展控件時會回調(diào)的方法,就是構(gòu)建一個原生控件返回
@WXComponentProp(name = "tel"):如果需要定義一個屬性,需要使用這個注解,name就是屬性名,在uniapp中創(chuàng)建控件時可以使用這個屬性傳入值,就會調(diào)用這個注解所在的方法,例如:通過tel屬性設置textview的內(nèi)容
@JSMethod:可以通過uniapp進行調(diào)用的方法,類似module擴展中的方法,不同的是這個是通過實例化的控件來調(diào)用
通過fireEvent可以反過來調(diào)用uniapp中定義的方法:特別注意:需要將方法參數(shù)放在detail中,否則你死活也接收不到參數(shù)的,然后fireEvent的第一個參數(shù)是uniapp中組件實例化時傳入的方法名,例如下面的@onTel,就應該傳入@符號后的名稱。
OK到這里component擴展插件的內(nèi)容也算寫好了,記下全類名com.elitetyc.elitetyc_plugin.TestComponentPlugin,后面注冊會用得到。
注意:module擴展插件還是component擴展插件里面的方法必須都為public,因為底層通過反射進行調(diào)用
uniapp頁面開發(fā)
image.png
修改index.vue內(nèi)容如下
? ? ? ?
點擊發(fā)行,生成離線打包資源
image.png
重點來了!!!!!!!!
在androidstudio原生項目的主項目下新建assert目錄,再新建一個apps文件夾,將剛才離線資源包復制到里面(離線資源包在uniapp的unpackage/resources目錄下),然后再復制SDK中的UniPlugin-Hello-AS/app/src/main/assets目錄下的data文件夾和dcloud_uniplugins.json文件復制到剛才新建的assert文件夾下,最后的目錄如下圖
image.png
然后重點又來了,需要修改data目錄下的dcloud_control.xml文件,修改里面的uniID,id就是剛才打包的離線資源包的文件夾名字,我這里修改后如下
<hbuilderversion="1.9.9.80137"><apps><appappid="__UNI__EA09775"appver=""/></apps></hbuilder>
[圖片上傳失敗...(image-c04a54-1589651166006)]
OK,這里的配置算是弄完了,接下來就是注冊!!!注冊!!!注冊!!!
也就是dcloud_uniplugins.json這個文件,修改后的內(nèi)容如下
{"nativePlugins":[{"plugins":[{"type":"module","name":"ElitetycModulePlugin","class":"com.elitetyc.elitetyc_plugin.TestModulePlugin"}]},{"plugins":[{"type":"component","name":"ElitetycText","class":"com.elitetyc.elitetyc_plugin.TestComponentPlugin"}]}]}
type:插件類型
name:插件名稱,這里很重要,uniapp代碼中uni.requireNativePlugin("ElitetycModulePlugin")相對應
class:這個就是我們寫的原生代碼全類名
到這里就大功告成了!!!,運行項目。
image.png