React Native 实现热更新并自动签名打包功能
项目背景:手动link的安卓App
1.下载react-native-code-push
npminstall--savereact-native-code-push
2.在android/settings.gradle文件下新增:
include':app',':react-native-code-push'
project(':react-native-code-push').projectDir=newFile(rootProject.projectDir,'../node_modules/react-native-code-push/android/app')
3.在android\app\src\main\java\com\app\MainApplication.java 文件中修改
... //1.Importthepluginclass. importcom.microsoft.codepush.react.CodePush; publicclassMainApplicationextendsApplicationimplementsReactApplication{ privatefinalReactNativeHostmReactNativeHost=newReactNativeHost(this){ ... //2.OverridethegetJSBundleFilemethodinordertolet //theCodePushruntimedeterminewheretogettheJS //bundlelocationfromoneachappstart @Override protectedStringgetJSBundleFile(){ returnCodePush.getJSBundleFile(); } //手动link需要修改的地方,自动link应该不需要改 @Override protectedListgetPackages(){ @SuppressWarnings("UnnecessaryLocalVariable") List packages=newPackageList(this).getPackages(); //Packagesthatcannotbeautolinkedyetcanbeaddedmanuallyhere,for //example: //packages.add(newMyReactNativePackage()); packages.add(newCodePush(getResources().getString(R.string.CodePushDeploymentKey), getApplicationContext(),BuildConfig.DEBUG, getResources().getString(R.string.reactNativeCodePush_androidServerURL))); returnpackages; } }; } //CodePushDeploymentKey对应string.xml里面的Deploymentkey的name //reactNativeCodePush_androidServerURL对应string.xml里面热更新服务地址的name
4.string.xml的修改:首先要将你的app添加到推送中心,并获取你需要的环境分支的key
4.1.登录热更新服务器
4.2.推送中心创建项目:(针对第一次部署)
code-pushappadd项目名称androidreact-native
4.3 添加环境分支dev:code-pushdeploymentadd项目名称dev(针对第一次部署)
将项目打包至对应的环境分支,需要将环境分支对应的key和热更新地址配置到项目文件中:(strings.xml)
4.4准备工作已经做好了,现在我们来修改string.xml文件吧
... applyfrom:"../../node_modules/react-native/react.gradle" applyfrom:"../../node_modules/react-native-code-push/android/codepush.gradle" ... dependencies{ implementationproject(':react-native-code-push')//最好手动加上,否则可能会有坑 implementationfileTree(dir:"libs",include:["*.jar"]) .... } ....
5.修改android/app/build.gradle文件
STACKTRACEAND/ORSCREENSHOTS :app:compileDebugJavaWithJavac-isnotincremental(e.g.outputshavechanged,nopreviousexecution,etc.). C:\StockApi\stock_app\android\app\src\main\java\com\stock_app\MainApplication.java:6:error:packagecom.microsoft.codepush.reactdoesnotexist importcom.microsoft.codepush.react.CodePush; ^ C:\StockApi\stock_app\android\app\src\main\java\com\stock_app\MainApplication.java:23:error:cannotfindsymbol returnCodePush.getJSBundleFile(); ^ symbol:variableCodePush C:\StockApi\stock_app\android\app\src\main\java\com\stock_app\MainApplication.java:35:error:cannotfindsymbol newCodePush(null,getApplicationContext(),BuildConfig.DEBUG), ^ symbol:classCodePush 3errors :app:compileDebugJavaWithJavacFAILED FAILURE:Buildfailedwithanexception. *Whatwentwrong: Executionfailedfortask':app:compileDebugJavaWithJavac'. >Compilationfailed;seethecompilererroroutputfordetails.
采坑:react-native-code-push需要手动添加依赖,否则会报错:
STACKTRACEAND/ORSCREENSHOTS
:app:compileDebugJavaWithJavac-isnotincremental(e.g.outputshavechanged,nopreviousexecution,etc.).
C:\StockApi\stock_app\android\app\src\main\java\com\stock_app\MainApplication.java:6:error:packagecom.microsoft.codepush.reactdoesnotexist
importcom.microsoft.codepush.react.CodePush;
^
C:\StockApi\stock_app\android\app\src\main\java\com\stock_app\MainApplication.java:23:error:cannotfindsymbol
returnCodePush.getJSBundleFile();
^
symbol:variableCodePush
C:\StockApi\stock_app\android\app\src\main\java\com\stock_app\MainApplication.java:35:error:cannotfindsymbol
newCodePush(null,getApplicationContext(),BuildConfig.DEBUG),
^
symbol:classCodePush
3errors
:app:compileDebugJavaWithJavacFAILED
FAILURE:Buildfailedwithanexception.
*Whatwentwrong:
Executionfailedfortask':app:compileDebugJavaWithJavac'.
>Compilationfailed;seethecompilererroroutputfordetails.
6.采坑:手动linkreact-native-code-push的app,需要禁止autolink,否则会报错:
java.lang.IllegalStateException:NativemoduleCodePushtriedtooverrideCodePushNativeModule.CheckthegetPackages()methodinMainApplication.java,itmightbethatmoduleisbeingcreatedtwice.Ifthiswasyourintention,setcanOverrideExistingModule=true
所以需要加上一个配置文件,禁止自动link
在项目根目录创建react-native.config.js文件
module.exports={ dependencies:{ 'react-native-code-push':{ platforms:{ android:null,//disableAndroidplatform,otherplatformswillstillautolink }, }, }, };
7.热更新配置完成,现在我们需要在项目启动的时候检测热更新,并提示
在项目入口文件App.js中:
importReact,{Component}from'react'; importRootfrom'./src/inner'; importconfigureStorefrom'./src/inner/store'; importUpdateDialogfrom'./src/common/components/updateDialog' importCodePushfrom"react-native-code-push"; const{persistor,store}=configureStore(); classAppextendsComponent{ state={ visitDialog:false, current:0, total:100 } componentDidMount(){ CodePush.sync({ //安装模式 //ON_NEXT_RESUME下次恢复到前台时 //ON_NEXT_RESTART下一次重启时 //IMMEDIATE马上更新 installMode:CodePush.InstallMode.IMMEDIATE, //对话框 updateDialog:{ //是否显示更新描述 appendReleaseDescription:true, //更新描述的前缀。默认为"Description" descriptionPrefix:"更新内容:", //强制更新按钮文字,默认为continue mandatoryContinueButtonLabel:"立即更新", //强制更新时的信息.默认为"Anupdateisavailablethatmustbeinstalled." mandatoryUpdateMessage:"必须更新后才能使用", //非强制更新时,按钮文字,默认为"ignore" optionalIgnoreButtonLabel:'稍后', //非强制更新时,确认按钮文字.默认为"Install" optionalInstallButtonLabel:'后台更新', //非强制更新时,检查到更新的消息文本 optionalUpdateMessage:'有新版本了,是否更新?', //Alert窗口的标题 title:'更新提示' }, }, (status)=>{ console.log(status,'status') if(status==7){ this.setState({visitDialog:true}) } }, (progress)=>{ letreceivedBytes=progress.receivedBytes/1024/1024; lettotalBytes=progress.totalBytes/1024/1024; this.setState({ current:receivedBytes, total:totalBytes }) if(receivedBytes===totalBytes){ setTimeout(()=>{ this.setState({visitDialog:false}) },1000) } console.log(progress,'progress') } ); } render(){ console.log(this.state.visitDialog,'visitDialog'); return( <>{this.state.visitDialog&& } > ) } }; letcodePushOptions={ //设置检查更新的频率 //ON_APP_RESUMEAPP恢复到前台的时候 //ON_APP_STARTAPP开启的时候 //MANUAL手动检查 checkFrequency:CodePush.CheckFrequency.ON_APP_START }; exportdefaultCodePush(codePushOptions)(App);
UpdateDialog:是我自己封装的热更新下载进度条的组件,下载提示,可根据自己的心情随便写,这里我就不贴自己的代码了!(写的不好,不好意思)
现在我们热更新配置好了,打包正式的apk吧!
1.生成签名文件:在项目根目录下运行命令:
keytool-genkey-v-keystore我的签名-key.jks-keyalgRSA-keysize2048-validity10000-alias我的签名
2.将生成的签名文件拷贝至目录:android/app目录下
3.配置gradle.properties
android.useAndroidX=true android.enableJetifier=true MYAPP_RELEASE_STORE_FILE=wms-app-key.jks//生成的签名密钥 MYAPP_RELEASE_KEY_ALIAS=ydh//别名 MYAPP_RELEASE_STORE_PASSWORD=签名时设置的密码 MYAPP_RELEASE_KEY_PASSWORD=签名时设置的密码
4.修改android/app/build.gradle
signingConfigs{ debug{ ... } release{ if(project.hasProperty('MYAPP_RELEASE_STORE_FILE')){ storeFilefile(MYAPP_RELEASE_STORE_FILE) storePasswordMYAPP_RELEASE_STORE_PASSWORD keyAliasMYAPP_RELEASE_KEY_ALIAS keyPasswordMYAPP_RELEASE_KEY_PASSWORD } } }
5..打包(android目录下):.\gradlew.batassembleRelease
app打包成功,将apk拷贝到手机安装即可
6..推送代码:(需要更新时,推送代码到你想要更新的环境分支)
推送到dev环境:code-pushrelease-react项目名称 android-ddev
推送到production环境:-mtrue代表强制更新,不加代表不强制更新
code-pushrelease-react项目名称android-dProduction-mtrue
然后重启app,就可以看到更新提示啦
总结
到此这篇关于ReactNative实现热更新并自动签名打包的文章就介绍到这了,更多相关ReactNative签名打包内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!