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))
				})
相关推荐
jyan_敬言2 小时前
【C++】string类(二)相关接口介绍及其使用
android·开发语言·c++·青少年编程·visual studio
程序员老刘2 小时前
Android 16开发者全解读
android·flutter·客户端
福柯柯3 小时前
Android ContentProvider的使用
android·contenprovider
不想迷路的小男孩3 小时前
Android Studio 中Palette跟Component Tree面板消失怎么恢复正常
android·ide·android studio
餐桌上的王子3 小时前
Android 构建可管理生命周期的应用(一)
android
菠萝加点糖3 小时前
Android Camera2 + OpenGL离屏渲染示例
android·opengl·camera
用户2018792831674 小时前
🌟 童话:四大Context徽章诞生记
android
yzpyzp4 小时前
Android studio在点击运行按钮时执行过程中输出的compileDebugKotlin 这个任务是由gradle执行的吗
android·gradle·android studio
aningxiaoxixi4 小时前
安卓之service
android
TeleostNaCl5 小时前
Android 应用开发 | 一种限制拷贝速率解决因 IO 过高导致系统卡顿的方法
android·经验分享