Flutter集成UniMPSDK(Uni小程序SDK)

Android 集成 UniMPSDK

1.下载并解压uni小程序 SDK。

SDK文件结构如下:

|--	SDK-Android@3.98-20231127
	|--	DEMO	//uni小程序SDK示例DEMO
	|--	SDK		//uni小程序SDK
		|--	assets	// assets资源文件
		|--	libs	//依赖库
		|--	res		// 资源文件
		|--	src		//微信分享支付需要的activity
		|-- proguard.cfg	//混淆配置

小程序打包基座:
提示:尽量与 UniMPSDK 版本一致

HBuilderX: 3.9.8
vue-cli @dcloudio/uvm版本: 3.0.0-3090820231124001

2.复制SDK资源到android项目相应的目录中。

libs依赖库配置

查看Flutter项目中android/app目录中是否存在libs文件夹,没有就创建。
SDK-Android@3.98-20231127/SDK/libs 中相应的依赖复制到 项目 android/app/libs/

libs 文件夹依赖库可根据功能需要进行增加或删除,除视频、地图、分享、支付、登录、直播pusher 等 SDK,只集成以下基础模块就可使用:

uniMPSDK-V2-release.aar  //必须集成,uni小程序sdk引擎需要
uniapp-v8-release.aar //必须集成,uni-app引擎需要
breakpad-build-release.aar //必须集成,breakpad用于采集系统崩溃日志
sqlite-release.aar
base_oaid_sdk.aar 必须集成 注意(3.3.8版本的SDK及以下版本请集成oaid_sdk_1.0.25.aar)
messaging-release.aar
iBeacon-release.aar
fingerprint-release.aar
contacts-release.aar
Bluetooth-release.aar
android-gif-drawable-release@1.2.23.aar //必须集成

assets 基础资源配置

1,将SDK-Android@3.98-20231127/SDK/assets/ 目录下的所有文件复制到 Flutter项目中android/app/src/main/assets/。(main目录下没有assets文件夹则自行创建)
2, Flutter项目中android/app/src/main/assets 目录中创建 apps 文件夹,用于放置 uni小程序打包发行的程序。
在小程序项目的 manifest.json 内获取并使用 uni-app 应用标识(AppID),也是我们之后指定操作小程序的标识。
vue-cli命令行打包:npm run build:app 生成本地包。
HBuilderX可视化界面打包:使用 【发行 => 原生App-本地打包 => 生成本地打包App资源】 生成本地包。
将打包好的uniapp小程序复制到apps文件下,apps文件夹结构必须如下:

├── apps
│   ├── __UNI__xxxxxxx  # 小程序1
│   │   └── www
│   │   │   └── ...     #小程序编码
│   ├── __UNI__xxxxxxx  # 小程序2
│   │   └── www
│   │   │   └── ...     #小程序编码 

proguard 混淆配置

SDK-Android@3.98-20231127/SDK/proguard.cfg 复制到Flutter项目中android/app/ 中。

3.修改android配置

修改MainActivity.kt配置文件

MainActivity.kt文件路径:Flutter项目/android/app/src/main/kotlin/com/example/xxxx/MainActivity.kt

package com.example.xxxx	//改成你自己的包名

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterFragmentActivity;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.Log
 
import io.dcloud.feature.sdk.DCUniMPSDK;
import io.dcloud.feature.sdk.Interface.IUniMP
import io.dcloud.feature.sdk.DCSDKInitConfig
import io.dcloud.feature.sdk.MenuActionSheetItem
import io.dcloud.common.adapter.util.Logger

class MainActivity: FlutterFragmentActivity() {
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
        val messenger = flutterEngine.dartExecutor.binaryMessenger
        // Channel 对象
        val channel = MethodChannel(messenger, "UniMP_mini_apps")
        // Channel 设置回调
        channel.setMethodCallHandler { call, res ->
            // 根据方法名,分发不同的处理
            when(call.method) {
                // 打开指定的 UniMP 小程序
                "open" -> {
                    try {
                        // 接收 Flutter 传入的参数
                        val argumentAppID = call.argument<String>("AppID")
                        // 设置右上角胶囊操作菜单
                        val item = MenuActionSheetItem("关于", "about")
                        val sheetItems: MutableList<MenuActionSheetItem> = ArrayList()
                        sheetItems.add(item)
                        // 初始化uniMPSDK
                        val config = DCSDKInitConfig.Builder()
                                .setCapsule(true)
                                .setMenuDefFontSize("16px")
                                .setMenuDefFontColor("#2D2D2D")
                                .setMenuDefFontWeight("normal")
                                .setMenuActionSheetItems(sheetItems)
                                .build()
                        DCUniMPSDK.getInstance().initialize(this, config)
 
                        // 打开小程序
                        val unimp: IUniMP = DCUniMPSDK.getInstance().openUniMP(this, argumentAppID)
                        // 监听胶囊菜单点击事件
                        DCUniMPSDK.getInstance().setDefMenuButtonClickCallBack { argumentAppID, id ->
                            when (id) {
                                "about" -> {
                                    Logger.e(argumentAppID + "点击了关于")
                                }
                            }
                        }
                        // 监听小程序关闭
                        DCUniMPSDK.getInstance().setUniMPOnCloseCallBack { argumentAppID -> Log.e("unimp", argumentAppID + "被关闭了") }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
 
                else -> {
                    // 如果有未识别的方法名,通知执行失败
                    res.error("error_code", "error_message", null)
                }
            }
        }
    }
} 

修改build.gradle配置文件

plugins {
    id "com.android.application"
    id "kotlin-android"
    id "dev.flutter.flutter-gradle-plugin"
}

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

android {
    namespace "com.example.life_app"
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.life_app"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        //uni小程序sdk配置
        ndk {
            abiFilters 'x86','x86_64','armeabi-v7a','arm64-v8a' // 不支持armeabi
        }
    }

    buildTypes {
        release {   //发布
            // 注意点:minifyEnabled 混淆和shrinkResources移除无用资源需同时为true或false,否则可能导致编译失败!
            minifyEnabled true  //是否进行混淆
            shrinkResources true  //删除无用资源
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro', 'proguard.cfg' //指定混淆规则文件
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug //设置签名信息
        }
    }
    //uni小程序sdk配置(此处配置必须添加 否则无法正确运行)
    aaptOptions {
        additionalParameters '--auto-add-overlay'
        //noCompress 'foo', 'bar'
        ignoreAssetsPattern "!.svn:!.git:.*:!CVS:!thumbs.db:!picasa.ini:!*.scc:*~"
    }
}

flutter {
    source '../..'
}

// uni小程序sdk配置(导入aar需要的配置)
repositories {
    flatDir {
        dirs 'libs'
    }
}

dependencies {
    //uni小程序sdk配置(导入SDK相关依赖jar、aar)
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation fileTree(include: ['*.aar'], dir: 'libs')
    //uni小程序sdk配置(必须添加的依赖)
    implementation 'androidx.recyclerview:recyclerview:1.0.0' //必须集成,android 自带recyclerview支持
    implementation 'androidx.legacy:legacy-support-v4:1.0.0' //必须集成,androidx support支持
    implementation 'androidx.appcompat:appcompat:1.0.0' //必须集成,androidx appcompat支持
    implementation 'com.alibaba:fastjson:1.2.83' //必须集成,fastjson功能需要
    implementation 'com.facebook.fresco:fresco:2.5.0'//必须集成,图片加载需要
    implementation 'com.facebook.fresco:animated-gif:2.5.0'//必须集成,图片加载需要
    implementation 'com.github.bumptech.glide:glide:4.9.0'//必须集成,图片加载需要
    implementation 'androidx.webkit:webkit:1.3.0' //3.6.15版本之后 必须集成,用来支持暗黑模式
}


4.Flutter项目中调用


  Widget build(BuildContext context) {
    const channel = MethodChannel('UniMP_mini_apps');

    Future callNativeMethod(String appID) async {
      try {
        // 通过通道,调用原生代码代码的方法
        final future = await channel.invokeMethod("open", {"AppID": appID});
        // 打印执行的结果
        print(future.toString());
      } on PlatformException catch (e) {
        print(e.toString());
      }
    }

    return Scaffold(
        body: Center(
      child: GestureDetector(
        onTap: () async {
          await callNativeMethod("__UNI__359FE36");
        },
        child: const Text('打开uni小程序'),
      ),
    ));
  }

本文参考以下链接:
https://amoshk.top/2022050801/

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值