您好,登錄后才能下訂單哦!
這篇文章主要講解了React Native如何實現熱更新并自動簽名打包功能,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
項目背景:手動link的安卓App
1.下載 react-native-code-push
npm install --save react-native-code-push
2.在android/settings.gradle文件下新增:
include ':app', ':react-native-code-push'
project(':react-native-code-push').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-code-push/android/app')
3.在android\app\src\main\java\com\app\MainApplication.java
文件中修改
... // 1. Import the plugin class. import com.microsoft.codepush.react.CodePush; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { ... // 2. Override the getJSBundleFile method in order to let // the CodePush runtime determine where to get the JS // bundle location from on each app start @Override protected String getJSBundleFile() { return CodePush.getJSBundleFile(); } //手動link需要修改的地方,自動link應該不需要改 @Override protected List<ReactPackage> getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List<ReactPackage> packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for // example: // packages.add(new MyReactNativePackage()); packages.add(new CodePush(getResources().getString(R.string.CodePushDeploymentKey), getApplicationContext(), BuildConfig.DEBUG, getResources().getString(R.string.reactNativeCodePush_androidServerURL))); return packages; } }; } //CodePushDeploymentKey對應string.xml里面的 Deployment key的name //reactNativeCodePush_androidServerURL對應string.xml里面熱更新服務地址的name
4.string.xml的修改:首先要將你的app添加到推送中心,并獲取你需要的環境分支的key
4.1.登錄熱更新服務器
4.2.推送中心創建項目:(針對第一次部署)
code-push app add 項目名稱 android react-native
4.3 添加環境分支dev:code-push deployment add 項目名稱 dev (針對第一次部署)
將項目打包至對應的環境分支,需要將環境分支對應的key和熱更新地址配置到項目文件中:(strings.xml)
4.4 準備工作已經做好了,現在我們來修改string.xml文件吧
... apply from: "../../node_modules/react-native/react.gradle" apply from: "../../node_modules/react-native-code-push/android/codepush.gradle" ... dependencies { implementation project(':react-native-code-push') //最好手動加上,否則可能會有坑 implementation fileTree(dir: "libs", include: ["*.jar"]) .... } ....
5.修改android/app/build.gradle文件
STACK TRACE AND/OR SCREENSHOTS :app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.). C:\Stock Api\stock_app\android\app\src\main\java\com\stock_app\MainApplication.java:6: error: package com.microsoft.codepush.react does not exist import com.microsoft.codepush.react.CodePush; ^ C:\Stock Api\stock_app\android\app\src\main\java\com\stock_app\MainApplication.java:23: error: cannot find symbol return CodePush.getJSBundleFile(); ^ symbol: variable CodePush C:\Stock Api\stock_app\android\app\src\main\java\com\stock_app\MainApplication.java:35: error: cannot find symbol new CodePush(null, getApplicationContext(), BuildConfig.DEBUG), ^ symbol: class CodePush 3 errors :app:compileDebugJavaWithJavac FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:compileDebugJavaWithJavac'. > Compilation failed; see the compiler error output for details.
采坑:react-native-code-push需要手動添加依賴,否則會報錯:
STACK TRACE AND/OR SCREENSHOTS
:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
C:\Stock Api\stock_app\android\app\src\main\java\com\stock_app\MainApplication.java:6: error: package com.microsoft.codepush.react does not exist
import com.microsoft.codepush.react.CodePush;
^
C:\Stock Api\stock_app\android\app\src\main\java\com\stock_app\MainApplication.java:23: error: cannot find symbol
return CodePush.getJSBundleFile();
^
symbol: variable CodePush
C:\Stock Api\stock_app\android\app\src\main\java\com\stock_app\MainApplication.java:35: error: cannot find symbol
new CodePush(null, getApplicationContext(), BuildConfig.DEBUG),
^
symbol: class CodePush
3 errors
:app:compileDebugJavaWithJavac FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
6.采坑:手動link react-native-code-push的app,需要禁止autolink,否則會報錯:
java.lang.IllegalStateException: Native module CodePush tried to override CodePushNativeModule. Check the getPackages() method in MainApplication.java, it might be that module is being created twice. If this was your intention, set canOverrideExistingModule=true
所以需要加上一個配置文件,禁止自動link
在項目根目錄創建react-native.config.js文件
module.exports = { dependencies: { 'react-native-code-push': { platforms: { android: null, // disable Android platform, other platforms will still autolink }, }, }, };
7.熱更新配置完成,現在我們需要在項目啟動的時候檢測熱更新,并提示
在項目入口文件App.js中:
import React,{ Component } from 'react'; import Root from './src/inner'; import configureStore from './src/inner/store'; import UpdateDialog from './src/common/components/updateDialog' import CodePush from "react-native-code-push"; const { persistor, store } = configureStore(); class App extends Component { 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: "立即更新", //強制更新時的信息. 默認為"An update is available that must be installed." mandatoryUpdateMessage: "必須更新后才能使用", //非強制更新時,按鈕文字,默認為"ignore" optionalIgnoreButtonLabel: '稍后', //非強制更新時,確認按鈕文字. 默認為"Install" optionalInstallButtonLabel: '后臺更新', //非強制更新時,檢查到更新的消息文本 optionalUpdateMessage: '有新版本了,是否更新?', //Alert窗口的標題 title: '更新提示' }, }, (status) => { console.log(status, 'status') if (status == 7) { this.setState({ visitDialog: true }) } }, (progress) => { let receivedBytes = progress.receivedBytes / 1024 / 1024; let totalBytes = 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 ( <> <Root store={store} persistor={persistor} /> {this.state.visitDialog && <UpdateDialog title={this.state.current === this.state.total ? '已完成' : '正在下載更新文件'} describe={this.state.current === this.state.total ? '歡迎使用' : '請耐心等待'} current={this.state.current} total={this.state.total}></UpdateDialog>} </> ) } }; let codePushOptions = { //設置檢查更新的頻率 //ON_APP_RESUME APP恢復到前臺的時候 //ON_APP_START APP開啟的時候 //MANUAL 手動檢查 checkFrequency: CodePush.CheckFrequency.ON_APP_START }; export default CodePush(codePushOptions)(App);
UpdateDialog :是我自己封裝的熱更新下載進度條的組件,下載提示,可根據自己的心情隨便寫,這里我就不貼自己的代碼了!(寫的不好,不好意思)
現在我們熱更新配置好了,打包正式的apk吧!
1. 生成簽名文件:在項目根目錄下運行命令:
keytool -genkey -v -keystore 我的簽名-key.jks -keyalg RSA -keysize 2048 -validity 10000 -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')) { storeFile file(MYAPP_RELEASE_STORE_FILE) storePassword MYAPP_RELEASE_STORE_PASSWORD keyAlias MYAPP_RELEASE_KEY_ALIAS keyPassword MYAPP_RELEASE_KEY_PASSWORD } } }
5..打包(android目錄下): .\gradlew.bat assembleRelease
app打包成功,將apk拷貝到手機安裝即可
6..推送代碼:(需要更新時,推送代碼到你想要更新的環境分支)
推送到dev環境:code-push release-react 項目名稱 android -d dev
推送到production環境:-m true 代表強制更新,不加代表不強制更新
code-push release-react 項目名稱 android -d Production -m true
然后重啟app,就可以看到更新提示啦
看完上述內容,是不是對React Native如何實現熱更新并自動簽名打包功能有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。