[android-studio] Build Android Studio app via command line

I want to build an Android Studio app (the Gradle build system), but I want to do this via the command line.

The answer is


Official Documentation is here:

To build a debug APK, open a command line and navigate to the root of your project directory. To initiate a debug build, invoke the assembleDebug task:

gradlew assembleDebug

This creates an APK named module_name-debug.apk in project_name/module_name/build/outputs/apk/.


You're likely here because you want to install it too!

Build

gradlew

(On Windows gradlew.bat)

Then Install

adb install -r exampleApp.apk

(The -r makes it replace the existing copy, add an -s if installing on an emulator)

Bonus

I set up an alias in my ~/.bash_profile, to make it a 2char command.

alias bi="gradlew && adb install -r exampleApp.apk"

(Short for Build and Install)


note, you can also do this within Android Studio by clicking the gradle window, and then the 'elephant' button. This will open a new window called "run anything" (can also be found by searching for that name in 'search everywhere') where you can manually type any gradle command you want in. Not "quite" command line, but often provides more of what I need than windows command line.

This allows you to give optional params to gradle tasks, etc.


Adding value to all these answers,

many have asked the command for running App in AVD after build sucessful.

adb install -r {path-to-your-bild-folder}/{yourAppName}.apk

For Mac use this command

  ./gradlew task-name

there are two build types to build your application using the Gradle build settings: one for debugging your application — debug — and one for building your final package for release — release mode.

Building in Debug Mode

  • First Navigate to Android studio project Root folder using CMD enter image description here

  • run this command gradlew.bat assembleDebug

  • Output window look like this enter image description here

Build signed apk in Release Mode

  • Edit the build.gradle file to build your project in release mode:

    android {
    ...
    defaultConfig { ... }
    signingConfigs {
        release {
            storeFile file("myreleasekey.keystore")
            storePassword "password"
            keyAlias "MyReleaseKey"
            keyPassword "password"
        }
    }
    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }
    }}
    

enter image description here

  • run this command gradlew.bat assembleRelease

Done.Good Luck!


Try this (OS X only):

brew install homebrew/versions/gradle110
gradle build

You can use gradle tasks to see all tasks available for the current project. No Android Studio is needed here.


Only for MAC Users

Extending Vji's answer.

Step by step procedure:

  1. Open Terminal
  2. Change your directory to your Project(cd PathOfYourProject)
  3. Copy and paste this command and hit enter:

    chmod +x gradlew
    
  4. As Vji suggested:

    ./gradlew task-name
    

    DON'T FORGOT TO ADD .(DOT) BEFORE /gradlew


1. Install Gradle and the Android SDK

Either

  • Install these however you see fit
  • Run ./gradlew, or gradlew.bat if on Windows
    • chmod +x ./gradlew may be necessary

From this point onwards, gradle refers to running Gradle whichever way you've chosen. Substitute accordingly.

2. Setup the Android SDK

  • If you've manually installed the SDK

    • export ANDROID_HOME=<install location>
    • You may want to put that in your ~/.profile if it's not done automatically
  • Accept the licenses: yes | sdkmanager --licenses

    • sdkmanager can be found in $ANDROID_HOME/tools/bin
    • sdkmanager may have to be run as root
  • Try running gradle

    • If there are complaints about licenses or SDKs not being found, fix the directory permissions
      • chown -R user:group $ANDROID_HOME
      • If you're reckless and/or the only user: chmod 777 -R $ANDROID_HOME

3. Building

  • gradle tasks lists all tasks that can be run
  • :app:[appname] is the prefix of all tasks, which you'll see in the Gradle logs when you're building
    • This can be excluded when running a task

Some essential tasks

  • gradle assemble: build all variants of your app
    • Resulting .apks are in app/[appname]/build/outputs/apk/[debug/release]
  • gradle assembleDebug or assembleRelease: build just the debug or release versions
  • gradle installDebug or installRelease build and install to an attached device
    • Have adb installed
    • Attach a device with USB debugging and USB file transfer enabled
    • Run adb devices, check that your device is listed and device is beside it

Automatically build and install upon changes

This avoids having to continuously run the same commands

gradle -t --continue installDebug
  • -t: aka --continuous, automatically re-runs the task after a file is changed
  • --continue: Continue after errors. Prevents stopping when errors occur

Run gradle -h for more help


enter code hereCreate script file with below gradle and adb command, Execute script file

./gradlew clean

./gradlew assembleDebug ./gradlew installDebug

adb shell am start -n applicationID/full path of launcher activity


Cheatsheet for running Gradle from the command line for Android Studio projects on Linux:

cd <project-root>
./gradlew
./gradlew tasks
./gradlew --help

Should get you started..


I faced the same problem and seems that there have been many changes by google.

I can tell you the steps for installing purely via command line from scratch. I tested it on Ubuntu on 22 Feb 2021.

create sdk folder

export ANDROID_SDK_ROOT=/usr/lib/android-sdk
sudo mkdir -p $ANDROID_SDK_ROOT

install openjdk

sudo apt-get install openjdk-8-jdk

download android sdk

Go to https://developer.android.com/studio/index.html Then down to Command line tools only Click on Linux link, accept the agreement and instead of downloading right click and copy link address

cd $ANDROID_SDK_ROOT
sudo wget https://dl.google.com/android/repository/commandlinetools-linux-6858069_latest.zip
sudo unzip commandlinetools-linux-6858069_latest.zip

move folders

Rename the unpacked directory from cmdline-tools to tools, and place it under $ANDROID_SDK_ROOT/cmdline-tools, so now it should look like: $ANDROID_SDK_ROOT/cmdline-tools/tools. And inside it, you should have: NOTICE.txt bin lib source.properties.

set path

PATH=$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin

This had no effect for me, hence the next step

browse to sdkmanager

cd $ANDROID_SDK_ROOT/cmdline-tools/tools/bin

accept licenses

yes | sudo sdkmanager --licenses

create build

Finally, run this inside your project

sudo ./gradlew assembleDebug

This creates an APK named -debug.apk at //build/outputs/apk/debug The file is already signed with the debug key and aligned with zipalign, so you can immediately install it on a device.

REFERENCES

https://gist.github.com/guipmourao/3e7edc951b043f6de30ca15a5cc2be40

Android Command line tools sdkmanager always shows: Warning: Could not create settings

"Failed to install the following Android SDK packages as some licences have not been accepted" error

https://developer.android.com/studio/build/building-cmdline#sign_cmdline


Examples related to android-studio

A failure occurred while executing com.android.build.gradle.internal.tasks "Failed to install the following Android SDK packages as some licences have not been accepted" error Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' Flutter plugin not installed error;. When running flutter doctor ADB.exe is obsolete and has serious performance problems Android design support library for API 28 (P) not working Flutter command not found How to find the path of Flutter SDK

Examples related to gradle

Gradle - Move a folder from ABC to XYZ A failure occurred while executing com.android.build.gradle.internal.tasks Gradle: Could not determine java version from '11.0.2' Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Failed to resolve: com.android.support:appcompat-v7:28.0 Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Examples related to command-line

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Flutter command not found Angular - ng: command not found how to run python files in windows command prompt? How to run .NET Core console app from the command line Copy Paste in Bash on Ubuntu on Windows How to find which version of TensorFlow is installed in my system? How to install JQ on Mac by command-line? Python not working in the command line of git bash Run function in script from command line (Node JS)

Examples related to android-gradle-plugin

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' Android Material and appcompat Manifest merger failed Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries Invoke-customs are only supported starting with android 0 --min-api 26 error: resource android:attr/fontVariationSettings not found Exception : AAPT2 error: check logs for details Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)