uniapp 开发之原生Android插件

开发须知

在您阅读此文档时,我们假定您已经具备了相应Android应用开发经验,使用Android Studio开发过Android原生。也应该对HTML,JavaScript,CSS等有一定的了解, 并且熟悉在JavaScript和JAVA环境下的JSON格式数据操作等。

为了插件开发者更方便快捷的开发uni原生插件!2.9.8版本起修改了uni插件开发API及规范。当然还会继续兼容老的插件运行及开发。推荐插件开发者按新版规范实现开发插件。方便日后更高效的更新迭代uni原生插件!

开发环境

新建Uni原生插件项目

  • 点击Android Studio菜单选项File--->New--->New Project。
  • 导入Uni SDK 官网下载对应的SDK SDK下载,在自己的libs 下导入自己需要的离线包
  • 开发插件

开发的插件必须导入uniapp-v8-release.aar,创建一个插件的module(本例以通知插件NotificationModule为例),插件开发有两种类型。

1、Module 扩展 非 UI 的特定功能.

2、Component 扩展 实现特别功能的 Native 控件

Groovy 复制代码
//必须添加的依赖
	compileOnly 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0',
	compileOnly 'androidx.core:core:1.1.0'
	compileOnly 'androidx.fragment:fragment:1.1.0'
	compileOnly 'androidx.appcompat:appcompat:1.1.0'
	compileOnly 'androidx.recyclerview:recyclerview:1.1.0'
	compileOnly 'com.alibaba:fastjson:1.2.83'

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

创建NotificationModule类

  • Module 扩展必须继承 UniModule 类
  • 扩展方法必须加上@UniJSMethod (uiThread = false or true) 注解。UniApp 会根据注解来判断当前方法是否要运行在 UI 线程,和当前方法是否是扩展方法。
  • UniApp是根据反射来进行调用 Module 扩展方法,所以Module中的扩展方法必须是 public 类型。
  • 同样因为是通过反射调用,Module 不能被混淆。请在混淆文件中添加代码:
复制代码
  -keep public class * extends io.dcloud.feature.uniapp.common.UniModule{*;}
  • Module 扩展的方法可以使用 int, double, float, String, Map, List ,com.alibaba.fastjson.JSONObject 类型的参数
java 复制代码
public class NotificationModule extends UniModule {
    /**
     * 发送通知
     * @param option
     * @param callback
     */
    @UniJSMethod(uiThread = true)
    public void sendNotice(JSONObject option, UniJSCallback callback){
        if (option==null){
            callback.invoke(PluginResultEntites.fail(-1,"参数不能为空"));
            return;
        }
        if (!option.containsKey("title")){
            callback.invoke(PluginResultEntites.fail(-1,"需要设置title参数(通知title)"));
            return;
        }
        if (TextUtils.isEmpty(option.getString("title"))){
            callback.invoke(PluginResultEntites.fail(-1,"参数title不能为空(通知title)"));
            return;
        }
        if (!option.containsKey("content")){
            callback.invoke(PluginResultEntites.fail(-1,"需要设置content参数(通知content)"));
            return;
        }
        if (TextUtils.isEmpty(option.getString("content"))){
            callback.invoke(PluginResultEntites.fail(-1,"参数content不能为空(通知content)"));
            return;
        }
        int resId = mUniSDKInstance.getContext().getResources().getIdentifier("ic_launcher", "mipmap", mUniSDKInstance.getContext().getPackageName());
        String title = option.getString("title");
        String content = option.getString("content");
        Intent intent = new Intent(mUniSDKInstance.getContext(), NotificationClickReceiver.class);
        intent.putExtra("type",10);
        intent.putExtra("noticeTitle",title);
        intent.putExtra("noticeContent",content);
        intent.putExtra("appID",option.getString("appID"));
        intent.putExtra("noticeExtras",option.containsKey("extras")?option.getString("extras"):"");
//        Intent intent = mUniSDKInstance.getContext().getPackageManager().getLaunchIntentForPackage(mUniSDKInstance.getContext().getPackageName());
        //普通通知栏消息
        NotificationUtils notificationUtils = new NotificationUtils(mUniSDKInstance.getContext(), 0, "13214345353", resId, title, content);
        notificationUtils.notifiedReceive(intent);
        callback.invoke(PluginResultEntites.success());

    }
}

扩展组件 Component

  • Component 扩展 实现特别功能的 Native 控件
  • Component 不支持代码中 new Component 创建对象。无法正常使用!

下面以TestComponent为例

java 复制代码
public class TestText extends UniComponent<TextView>{
    //创建对象
    @Override
    protected TextView initComponentHostView(@NonNull Context context) {
        TextView textView = new TextView(context);
        textView.setTextSize(20);
        textView.setTextColor(Color.BLACK);
        return textView;
    }

    //设置电话号码
    @UniComponentProp(name = "tel")
    public void setTel(String telNumber) {
        getHostView().setText("tel: " + telNumber);
    }
    
    //清空电话号码
    @UniJSMethod
    public void clearTel() {
       getHostView().setText("");
    }

}
  • 注册组之后,你可以在nvue 文件中调用
javascript 复制代码
<template>
	<div>
		<myText ref="telText" tel="12305" style="width:200;height:100" @onTel="onTel" @click="myTextClick"></myText>
	</div>
</template>
<script>
    export default {
        methods: {
			myTextClick(e) {
				this.$refs.telText.clearTel();
			}
        }
    }
</script>

注册插件

主要介绍json的方式注册新创建的插件,现在新建截图的文件,在主项目的app asset目录下创建。

在dcloud_uniplugins.json中注册新建的插件

javascript 复制代码
{
      "plugins": [
        {
          "type": "module",
          "name": "NotificationModule",
          "class": "com.kairison.applet.plugin.eachother.notice.NotificationModule"
        }
      ]
    }

在uni-app项目中获取插件,通过requireNativePlugin 来获取插件,本例子以NotificationModule

javascript 复制代码
const notificationModule = uni.requireNativePlugin('NotificationModule')
	notificationModule.sendNotice({
					title: '测试通知',
                    content: '测试内容',
                    
				}, (res) => {
                    console.log(JSON.stringify(res.data))
				})
相关推荐
Mr_li6 小时前
给 Vue 开发者的 uni-app 快速指南
vue.js·uni-app
anyup8 小时前
🔥2026最推荐的跨平台方案:H5/小程序/App/鸿蒙,一套代码搞定
前端·uni-app·harmonyos
阿巴斯甜11 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker12 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq952713 小时前
Andorid Google 登录接入文档
android
黄林晴14 小时前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab1 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿1 天前
Android MediaPlayer 笔记
android
Jony_1 天前
Android 启动优化方案
android
阿巴斯甜1 天前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android