From e32336b96fca3bbc3b1e72c4fb5a474352aebfcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sa=C3=BAl=20Ibarra=20Corretg=C3=A9?= Date: Wed, 20 Mar 2019 15:14:42 +0100 Subject: [PATCH] android: run the React packager when running from AS When running the app from Android Studio the React packager is not automatically started. In vanilla RN projects this is done by the "react-native run-android" command, but often times it is desired to run from Android Studio. This fixes that by starting the packager from Gradle. --- android/app/build.gradle | 35 +++++++++++++++++++++++++++++++++ android/scripts/run-packager.sh | 24 ++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100755 android/scripts/run-packager.sh diff --git a/android/app/build.gradle b/android/app/build.gradle index 092000c55..1c9edffdf 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -116,6 +116,41 @@ gradle.projectsEvaluated { } } } + + // Run React packager + android.applicationVariants.all { variant -> + def targetName = variant.name.capitalize() + + def currentRunPackagerTask = tasks.create( + name: "run${targetName}ReactPackager", + type: Exec) { + group = "react" + description = "Run the React packager." + + doFirst { + println "Starting the React packager..." + + def androidRoot = file("${projectDir}/../") + + // Set up the call to the script + workingDir androidRoot + + // Run the packager + commandLine("scripts/run-packager.sh") + } + + // Set up dev mode + def devEnabled = !targetName.toLowerCase().contains("release") + + // Only enable for dev builds + enabled devEnabled + } + + def packageTask = variant.packageApplicationProvider.get() + + packageTask.dependsOn(currentRunPackagerTask) + } + } if (googleServicesEnabled) { diff --git a/android/scripts/run-packager.sh b/android/scripts/run-packager.sh new file mode 100755 index 000000000..d57658318 --- /dev/null +++ b/android/scripts/run-packager.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +# This script is executed bt Gradle to start the React packager for Debug +# targets. + +THIS_DIR=$(cd -P "$(dirname "$(readlink "${BASH_SOURCE[0]}" || echo "${BASH_SOURCE[0]}")")" && pwd) + +export RCT_METRO_PORT="${RCT_METRO_PORT:=8081}" +echo "export RCT_METRO_PORT=${RCT_METRO_PORT}" > "${THIS_DIR}/../../node_modules/react-native/scripts/.packager.env" + +if nc -w 5 -z localhost ${RCT_METRO_PORT} ; then + if ! curl -s "http://localhost:${RCT_METRO_PORT}/status" | grep -q "packager-status:running" ; then + echo "Port ${RCT_METRO_PORT} already in use, packager is either not running or not running correctly" + exit 2 + fi +else + CMD="${THIS_DIR}/../../node_modules/react-native/scripts/launchPackager.command" + if [[ `uname` == "Darwin" ]]; then + open -g "${CMD}" || echo "Can't start packager automatically" + else + xdg-open "${CMD}" || echo "Can't start packager automatically" + fi +fi +