uniapp import (android) jar

Official Document: Notes for Developers | uni Mini Program SDK

1. Download the corresponding sample code and tools

2. Project preparation (unzip the downloaded project SDK and import it into Android Studio)

Click on android-project to see other files

Example delete

 

Delete the plugin registration

3. Create a new module (used to import jar and generate plug-ins for use by uniapp)

 

 An error will be reported after creation

 

 Find AndroidManifest.xml under module and add package="package path under java"

 Comment namespace click try again, found success

The jars that need to be imported can be placed under libs

Module-->build.gradle references the jar of the app and the jar imported by itself

compileOnly fileTree(include: ['uniapp-v8-release.aar'], dir: '../app/libs')
implementation fileTree(dir: '../uniplugin_scan/libs', include: ['*.aar', '*.jar'], exclude: [])

 Import dependencies:

compileOnly 'androidx.recyclerview:recyclerview:1.2.1'
compileOnly 'androidx.legacy:legacy-support-v4:1.0.0'
compileOnly 'com.alibaba:fastjson:1.1.46.android'

Click Sync Now in the upper right corner to refresh dependencies

4. Write the plug-in class

 ScanModule

package com.example.uniplugin_scan;

import android.content.Context;
import com.alibaba.fastjson.JSONObject;
import com.huayusoft.barcodeadmin.IScanCallBack;
import com.raindi.scanner.RDManager;
import com.taobao.weex.bridge.JSCallback;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.common.UniModule;

/**
 * 这边需要继承UniModule
 */
public class ScanModule extends UniModule {
    
    /**
     * uiThread = false  run JS thread 使用js线程
     * 测试提示
     * UniJSMethod 这个注册是uni通过反射可以获得对接的方法
     * @param options json参数
     * @param callback 回调
     */
    @UniJSMethod(uiThread = true)
    public void tips(JSONObject options, JSCallback callback){
        if(callback != null) {
            JSONObject data = new JSONObject();
            data.put("name", "调用插件成功");
            //回调返回
            callback.invoke(data);
        }
    }


    /**
     * uiThread = true  run ui thread 一般用于非耗时操作
     * 使用第三方包实现扫描条码
     * @param options json参数
     * @param callback 回调
     */
    @UniJSMethod(uiThread = true)
    public void scan(JSONObject options, JSCallback callback){
        if(callback != null) {
            JSONObject data = new JSONObject();
            //导入jar包的回调定义
            IScanCallBack callback1 =new IScanCallBack.Stub() {
                @Override
                public void onSuccess(final String bean) {
                    //接收条码服务返回的数据
                    data.put("name", bean);
                    System.out.println(bean);
                    callback.invoke(data);
                }
                @Override
                public void onFiled(int errorCode) {
                    //条码服务出错的数据
                    data.put("name", "服务出错");
                }
            };

            //创建扫描对象
            RDManager instance = RDManager.getInstance();
            //获得窗口
            Context context = this.mWXSDKInstance.getContext();
            //绑定扫描
            boolean b = instance.bindScannerService(context,callback1 );
            //初始化扫描
            instance.init(callback1);
            //开启电源
            instance.powerOn();
            //开始扫描
            instance.doScan();
        }
    }

    
}

Plug-in registration app--"src--"asset-->dcloud_uniplugins.json

{
  "nativePlugins": [
    {
      "plugins": [
        {
          "type": "module",
          "name": "Uni-Plugin-Scan",
          "class": "com.example.uniplugin_scan.ScanModule"
        }
      ]
    }
  ]
}

 Dependency add plugin app--"build.gradle

 implementation project(':uniplugin_scan')

 5. Write Uniapp

Create a new project and choose a common template

Write index.vue under pages

<template>
	<view class="content">
		<div>
			<button type="primary" @click="testTips">testTips</button>
			<button type="success" @click="testScan">testScan</button>
		</div>
	</view>
</template>

<script>
	// 获取 module,里面填插件名刚刚安卓的dcloud_uniplugins.json文件注册的插件名称
	var sc = uni.requireNativePlugin("Uni-Plugin-Scan") 
	export default {
		onLoad() {
			
		},
		methods: {
			testTips() {
				//调用插件的tips方法
				var ret = sc.tips({
				},(res)=>{
					 uni.showToast({
						title:res.name
					})
				})
			},
			testScan(){
				//调用插件的scan方法
				var ret = sc.scan({
				},(res)=>{
					 uni.showToast({
						title:res.name
					})
				})
			}
		}
	}
</script>

6. Generate local resources and put them into the android project

 find the resource file

 

 Copy to apps

 7. Register Android Key

Here I read the blog here, and the registration key can be written step by step.

uni-app official demo (Android sdk): The appkey is not configured or configured incorrectly. (Uni native plug-in development, Android plug-in development)

My own configuration, after configuration, click Sync Now in the upper right corner to refresh gradle (if the app key is not configured, please check whether the following fields are correct!!!!!)

 signature

 

8. run

Plug in the data cable to connect to the mobile phone, set usb debugging on the mobile phone to allow, android studio will recognize the device, so that it can run directly on android

 If an error occurs, please check the build.gradle configuration (especially the version and dependencies), the following is my build.gradle configuration

app build:gradle

apply plugin: 'com.android.application'

android {

    compileSdkVersion 33
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "com.android.UniPlugin"
        minSdkVersion 21
        targetSdkVersion 33 //建议此属性值设为21 io.dcloud.PandoraEntry 作为apk入口时   必须设置 targetSDKVersion>=21 沉浸式才生效

        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        ndk {
            abiFilters 'x86','armeabi-v7a'
        }
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }

    signingConfigs {
        config {
            keyAlias '__uni__****请填写自己的别名'
            keyPassword 'key的密码'
            storeFile file('对应的签名文件')
            storePassword 'stroe密码'
            v1SigningEnabled true
            v2SigningEnabled true
        }
    }

    buildTypes {
        release {
            signingConfig signingConfigs.config
            zipAlignEnabled true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            signingConfig signingConfigs.config
            zipAlignEnabled true
            minifyEnabled true
            proguardFiles 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 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.appcompat:appcompat:1.0.0'

    /*uniapp所需库-----------------------开始*/
    implementation 'androidx.recyclerview:recyclerview:1.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_scan')
//    implementation project(':uniplugin_component')
//    implementation project(':uniplugin_module')
//    implementation project(':uniplugin_richalert')
}

 module(uniplugin_scan) build.gradle

plugins {
    id 'com.android.library'
}

android {
    compileSdk 29

//    namespace 'com.example.uniplugin_scan'
//    compileSdkVersion 32

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 33

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        consumerProguardFiles "consumer-rules.pro"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildToolsVersion '28.0.3'
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    //必须导入的依赖
    compileOnly 'androidx.recyclerview:recyclerview:1.1.0'
    compileOnly 'androidx.legacy:legacy-support-v4:1.0.0'
    compileOnly 'com.alibaba:fastjson:1.1.46.android'

    //导入jar
    compileOnly fileTree(include: ['uniapp-v8-release.aar'], dir: '../app/libs')
    implementation fileTree(dir: '../uniplugin_scan/libs', include: ['*.aar', '*.jar'], exclude: [])
}

Through comparison and modification, it can be run without accident.

Screenshot of mobile phone running successfully

scanning

9. Package the andorid project and call it with uniapp

 

 Search for aar in the project folder

Copy the aar to the android folder below

 

 Configure package.json (remember to delete the comment, this cannot be written wrong, and wrong writing will cause the subsequent plug-ins to fail to recognize)

{
	"name": "AndroidScan", //插件名
    "id": "Uni-Plugin-Scan", //id
    "version": "0.0.2",
    "description": "安卓条码扫描",
    "_dp_type":"nativeplugin",
    "_dp_nativeplugin":{
        "android": {
            "plugins": [
                {
                    "type": "module",
                    "name": "Uni-Plugin-Scan", //插件名称一般和id相同或以id为前缀
                    "class": "com.example.uniplugin_scan.ScanModule" //andorid插件对应类的路径
                }
            ],
			"integrateType": "aar" //类型分为jar和aar
		}
	}
}

plugin configuration

 

 10. uniapp running

Custom base --- "direct packaging

 

 Just run it. If there is no device refresh, try to refresh it. If it still does not, please check whether the mobile phone is connected to the computer, whether it is debuggable, and whether it is file transfer.

 The operation is successful!!! The result is the same as the above android operation, so there is no screenshot here.

For more details, please refer to the official document: Notes for Developers | uni Mini Program SDK

Guess you like

Origin blog.csdn.net/ysfengshu/article/details/128189362