flutter开发实战-实现多渠道打包及友盟统计(亲测有效)

本文主要是介绍flutter开发实战-实现多渠道打包及友盟统计(亲测有效),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

flutter开发实战-实现多渠道打包及友盟统计(亲测有效)

最近开发过程中,需要引入友盟进行统计服务。友盟统计还需要区分不同渠道的打开应用的情况,所以需要处理多渠道打包的问题。

一、引入友盟统计

在工程的pubspec.yaml中引入插件

  // 在工程 pubspec.yaml 中加入 dependencies:umeng_common_sdk: ^1.2.3

导入及调用初始化友盟

import 'package:umeng_common_sdk/umeng_common_sdk.dart';

调用友盟统计

@overridevoid initState() {super.initState();initPlatformState();UmengCommonSdk.initCommon('5e3f96f3cb23d2a070000048', '5e3f96f3cb23d2a070000048', 'Umeng');UmengCommonSdk.setPageCollectionModeManual();}

这里需要填写channel渠道名后续我们需要根据打包的渠道来设置。

二、flutter代码中获取渠道

Flutter命令工具增加了自定义参数的功能 --dart-define,可以用这个命令参数在打包或运行 App 时设置参数。

如:

flutter run --dart-define=CHANNEL=YYB

在lib/main.dart中定义变量配置,可以方便调用

/// 定义环境变量配置
class EnvironmentConfig {static const CHANNEL = String.fromEnvironment('CHANNEL');
}

在需要的地方调用获取渠道名

  String currentChannel = "";@overridevoid initState() {// TODO: implement initStatesuper.initState();// 获取CHANNEL 参数值String channel = EnvironmentConfig.CHANNEL;print("channel:${channel}");currentChannel = channel;setState(() {});}

显示渠道名

            Container(height: 136,width: 300,color: Colors.lightGreen,alignment: Alignment.center,child: Text('当前渠道:${currentChannel}',style: TextStyle(fontSize: 12, color: Colors.white),),),

最终获得渠道显示效果图如下

在这里插入图片描述

三、android中gradle配置

我们需要在android/app/build.gradle中添加一下配置


/// 获取渠道参数使用,这里设置一下默认值
def dartEnvironmentVariables = [CHANNEL: 'guanfang-app',
]if (project.hasProperty('dart-defines')) {dartEnvironmentVariables = dartEnvironmentVariables + project.property('dart-defines').split(',').collectEntries { entry ->def pair = new String(entry.decodeBase64(), 'UTF-8').split('=')[(pair.first()): pair.last()]}
}

在输出的apk中,添加对应渠道名,在android一下${dartEnvironmentVariables.CHANNEL}进行区分不同渠道的apk名称。

ext {publishName = 'AppDemoLab'
}android {android.applicationVariants.all {variant ->variant.outputs.all {def buildTime = new Date().format('yyyyMMddHHmm')outputFileName = "${project.publishName}_${variant.versionName}_${variant.versionCode}_${buildTime}_${variant.buildType.name}_${dartEnvironmentVariables.CHANNEL}.apk"}}
}

打包与测试命令

# 调试例子1:设置渠道为应用宝。
flutter run --dart-define=CHANNEL=YYB#打包例子1:打包应用宝渠道包
flutter build apk --dart-define=CHANNEL=YYB

可以是多个–dart-define,如:

#打包例子2:打包应用宝渠道包,DEBUG参数是Y
flutter build apk --dart-define=CHANNEL=YYB --dart-define=DEBUG=Y

四、apk.sh多渠道打包脚本

在脚本中定义了渠道channels=(YYB HUAWEI MI OPPO VIVO)

在工程目录下创建shell目录,将apk.sh放到shell目录下。
在工程目录下创建prod目录,prod目录下创建apk目录,用于存放打包的渠道apk文件

apk.sh多渠道打包脚本如下

#!/bin/sh#---------------------请修改渠道数组----------------#
channels=(YYB HUAWEI MI OPPO VIVO)#当前工程绝对路径
project_path=$(pwd)#安卓包product文件夹路径
prod_path=${project_path}/prod/apk/
#Flutter打包生成的最初地址
release_path=${project_path}/build/app/outputs/apk/release/clean_tips="执行flutter clean(默认:n) [ y/n ]"
echo $clean_tips
read  -t 5 is_clean
if [  ! -n "${is_clean}" ];thenis_clean="n"
fi
while([[ $is_clean != "y" ]] && [[ $is_clean != "n" ]])
doecho "错误!只能输入[ y/n ] !!!"echo $clean_tipsread is_clean
donetips="请输入选择渠道(默认:0) [ ALL: 0 "
c_length=${#channels[@]};
for(( i=0; i<$c_length; i++)) doif (($i < $c_length-1 )); thentips="${tips}${channels[i]}: $((i+1)) "elsetips="${tips}${channels[i]}: $((i+1)) ]"fi
done;echo $tips
read  -t 5 number
if [  ! -n "${number}" ];thennumber=0
fi
while(( $number < "0" || $number > $c_length ))
doecho "错误!只能输入0到${c_length} !!!"echo $tipsread number
done#如果有product/apk文件夹则删除,然后再创建一个空文件夹
if [ -d ${prod_path} ]; thenrm -rf ${prod_path}
fi
#创建目录
mkdir -p ${prod_path}if [ ${is_clean} = "y" ];thenecho "=============== 开始清理 ==============="flutter clean
fiif (($number == 0 )); thenecho "=============== 开始构建:全部渠道包 ==============="for(( i=0;i<${c_length};i++)) doecho "正在构建:${channels[$i]} 渠道包"flutter build apk --no-shrink --dart-define=CHANNEL=${channels[$i]}cp -R ${release_path}*.apk ${prod_path}done;
elseecho "=============== 正在构建:${channels[$((number-1))]} 渠道包 ==============="flutter build apk --no-shrink --dart-define=CHANNEL=${channels[$((number-1))]}cp -R ${release_path}*.apk ${prod_path}
fi#判断apk目录下是否有文件
if [ "$(ls -A $prod_path)" ]; thenecho "=============== APK包已导出:$prod_path ==============="open $prod_path
elseecho '=============== APK包导出失败 ==============='exit 1
fi
exit 0

查看脚本可以看出

控制是否执行flutter clean
输入是全部渠道打包
打包后的apk拷贝到prod/apk文件夹下。

通过cd切换到shell目录下,执行apk.sh脚本进行多渠道打包

./shell/papk.sh

在prod/apk目录下,可以看到打包的apk
在这里插入图片描述

参考:https://github.com/sugood/flutter_shell

五、更改友盟渠道

在文中,使用友盟时候,需要传递渠道名,我们通过EnvironmentConfig.CHANNEL拿到渠道名后作为参数传给友盟。
友盟即可根据渠道进行统计。

六、附录(完整的gradle配置)

android/build.gradle配置如下

buildscript {ext.kotlin_version = '1.7.10'repositories {maven { url "https://maven.aliyun.com/repository/google" }maven { url "https://maven.aliyun.com/repository/central" }maven { url "https://maven.aliyun.com/repository/jcenter" }}dependencies {classpath 'com.android.tools.build:gradle:7.2.0'classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"}
}allprojects {repositories {maven { url "https://maven.aliyun.com/repository/google" }maven { url "https://maven.aliyun.com/repository/central" }maven { url "https://maven.aliyun.com/repository/jcenter" }}
}rootProject.buildDir = '../build'
subprojects {project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {project.evaluationDependsOn(':app')
}task clean(type: Delete) {delete rootProject.buildDir
}

android/app/build.gradle配置如下

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {localPropertiesFile.withReader('UTF-8') { reader ->localProperties.load(reader)}
}def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {flutterVersionCode = '1'
}def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {flutterVersionName = '1.0'
}def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}/// 获取渠道参数使用,这里设置一下默认值
def dartEnvironmentVariables = [CHANNEL: 'GuanFang',
]if (project.hasProperty('dart-defines')) {dartEnvironmentVariables = dartEnvironmentVariables + project.property('dart-defines').split(',').collectEntries { entry ->def pair = new String(entry.decodeBase64(), 'UTF-8').split('=')[(pair.first()): pair.last()]}
}ext {publishName = 'AppDemoLab'
}apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"android {compileSdkVersion 34ndkVersion flutter.ndkVersioncompileOptions {sourceCompatibility JavaVersion.VERSION_1_8targetCompatibility JavaVersion.VERSION_1_8}defaultConfig {// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).applicationId "com.example.flutter_app_demolab"// 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 21targetSdkVersion flutter.targetSdkVersionversionCode flutterVersionCode.toInteger()versionName flutterVersionNamendk {abiFilters "armeabi-v7a", "arm64-v8a"}}buildTypes {release {// 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}}android.applicationVariants.all {variant ->variant.outputs.all {def buildTime = new Date().format('yyyyMMddHHmm')outputFileName = "${project.publishName}_${variant.versionName}_${variant.versionCode}_${buildTime}_${variant.buildType.name}_${dartEnvironmentVariables.CHANNEL}.apk"}}
}flutter {source '../..'
}

七、小结

flutter开发实战-实现多渠道打包及友盟统计(亲测有效),根据自身需求调整后亲测有效,可以根据渠道来做一些代码上的区分。

学习记录,每天不停进步。

本文地址:https://brucegwo.blog.csdn.net/article/details/138907985

快快微信扫码玩一玩小游戏吧

战机长空小绳套牛
在这里插入图片描述在这里插入图片描述

这篇关于flutter开发实战-实现多渠道打包及友盟统计(亲测有效)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/993933

相关文章

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

SQL Server跟踪自动统计信息更新实战指南

《SQLServer跟踪自动统计信息更新实战指南》本文详解SQLServer自动统计信息更新的跟踪方法,推荐使用扩展事件实时捕获更新操作及详细信息,同时结合系统视图快速检查统计信息状态,重点强调修... 目录SQL Server 如何跟踪自动统计信息更新:深入解析与实战指南 核心跟踪方法1️⃣ 利用系统目录

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

PyQt5 GUI 开发的基础知识

《PyQt5GUI开发的基础知识》Qt是一个跨平台的C++图形用户界面开发框架,支持GUI和非GUI程序开发,本文介绍了使用PyQt5进行界面开发的基础知识,包括创建简单窗口、常用控件、窗口属性设... 目录简介第一个PyQt程序最常用的三个功能模块控件QPushButton(按钮)控件QLable(纯文本