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))
				})
相关推荐
CYRUS_STUDIO19 小时前
Frida 检测与对抗实战:进程、maps、线程、符号全特征清除
android·逆向
csj5020 小时前
安卓基础之《(28)—Service组件》
android
lhbian1 天前
PHP、C++和C语言对比:哪个更适合你?
android·数据库·spring boot·mysql·kafka
catoop1 天前
Android 最佳实践、分层架构与全流程解析(2025)
android
ZHANG13HAO1 天前
Android 13 特权应用(Android Studio 开发)调用 AOSP 隐藏 API 完整教程
android·ide·android studio
田梓燊1 天前
leetcode 142
android·java·leetcode
angerdream1 天前
Android手把手编写儿童手机远程监控App之JAVA基础
android
菠萝地亚狂想曲1 天前
Zephyr_01, environment
android·java·javascript
sTone873751 天前
跨端框架通信机制全解析:从 URL Schema 到 JSI 到 Platform Channel
android·前端
sTone873751 天前
Java 注解完全指南:从 "这是什么" 到 "自己写一个"
android·前端