Build an APK on unity using a command on the terminal - android

I have a project on Unity3d (working on a mac) and I am trying to generate the android apk file from the command line. Is this doable?
Right now I have a PerformBuild.cs file inside Assets/Editor
and I call inside it:
BuildPipeline.BuildPlayer(scenes, path, BuildTarget.Android, BuildOptions.AcceptExternalModificationsToPlayer);
However this is only generating the Android Project for it, and not the apk.
Can I directly generate the APK using a cs build script or will I have to generate the project, import it to eclipse and then build the apk?
Thank you
Additional information:
Here is the full method in my script
[UnityEditor.MenuItem("CUSTOM/Test Android Build Step")]
static void androidBuild ()
{
Debug.Log("Command line build android version\n------------------\n------------------");
string[] scenes = GetBuildScenes();
string path = GetBuildPathAndroid();
if(scenes == null || scenes.Length==0 || path == null)
return;
Debug.Log(string.Format("Path: \"{0}\"", path));
for(int i=0; i<scenes.Length; ++i)
{
Debug.Log(string.Format("Scene[{0}]: \"{1}\"", i, scenes[i]));
}
Debug.Log("Starting Android Build!");
BuildPipeline.BuildPlayer(scenes, path, BuildTarget.Android, BuildOptions.AcceptExternalModificationsToPlayer);
BuildPipeline.buil
}
and I call it from the command line using the following:
/Applications/Unity/Unity.app/Contents/MacOS/Unity -batchmode -quit -executeMethod PerformBuild.androidBuild
and I have the android sdk setup and configured

Just remove AcceptExternalModificationsToPlayer from the BuildOptions.
BuildOptions.AcceptExternalModificationsToPlayer
On Android, this setting will create a new Eclipse project. Existing Eclipse project setting changes will be discarded.
Source:
http://docs.unity3d.com/ScriptReference/BuildOptions.AcceptExternalModificationsToPlayer.html
Ok, I must admit, it's not 100% clear from this, but this is the "switch" to change, to build directly an .apk file instead of creating an Android project.
So in your case, just change
BuildPipeline.BuildPlayer(scenes, path, BuildTarget.Android, BuildOptions.AcceptExternalModificationsToPlayer);
to
BuildPipeline.BuildPlayer(scenes, path, BuildTarget.Android, BuildOptions.None);
You may want to take a look at all the different BuildOptions e.g. if you want to make your build debuggable (to be able to attach the MonoDevelop debugger to it => BuildOptions.Development | BuildOptions.AllowDebugging)
Source:
http://docs.unity3d.com/ScriptReference/BuildOptions.html

d4Rk is right, buil doption should be set to none, unless you know what you are doing.
I encountered same issue recently, searched and drilled for one day.
Just found a special line in my build tool script:
EditorUserBuildSettings.exportAsGoogleAndroidProject = true;
I don't remember when I wrote it.. so just commented it and the buildpipeline build apk agian..

Related

How to get an ENV var available in project which uses Android.mk

I have an Android project which uses Android.mk files for the setup. I would like to introduce Build Variants to the project and based on a build var such as BUILD_BRAND to perform some UI changes.
My case is:
I have BUILD_BRAND exported on my Ubuntu in the .bashrc.
If I echo $BUILD_BRAND I would get the value printed in the terminal.
I also do $(warning $(BUILD_BRAND)) and I can see during the build the value is printed so it is available.
But when I try to do System.getEnv("BUILD_BRAND"); in an activity, a null is returned.
The question is how to make this value under BUILD_BRAND to become globally available to the project.
Thanks!
In my case the solution was to use SystemProperties.get("the.property.name").
The "the.property.name" was set in the Makefile.mk located in the core.
I also find out that I can export ENV vars to the project during build time using the same Makefile.mk.
N.B - You can't access an env var during runtime directly using System.getEnv() !

Visual Studio 2017 Cordova; change target folder for Android build

I have figured out how to get visual studio to compile and test with cordova 7.1.0 even though in theory it is supposed to only work with 6.3.1 But I have one more issue with Android.
Deploy is looking for the apk in platforms\android\build\outputs\apk
Build now puts the apk in platforms\android\build\outputs\apk\debug
So if I build it, then copy the apk then tell visual studio to debug, it works since it can fine the apk in platforms\android\build\outputs\apk
So every time I want to test, I have to delete the apk, built it, then copy it, then build it again to allow visual studio to deploy it.
Is there a setting in visual studio, the project, or the registry that I can use to change either the deploy folder or the build folder so they match?
I followed the advice from here https://stackoverflow.com/a/49270052/9874134 but tweaked it a bit to make it work for my case.
The cordova android platform 6.4+ puts the built apk here:
[project]\platforms\android\app\build\outputs\apk\debug\app-debug.apk
Visual Studio seems to be looking for it here:
[project]\platforms\android\build\outputs\apk\app-debug.apk
I added an "after_build" hook that copies the app-debug.apk and
output.json files to the folder VS is looking in. I had to manually
add the folder structures (for both the location of files being copied
and location of hook file). I just added the following file, and the
build process picks it up automatically.
The next step is a bit different to the advice. The "after_build" hook copies the app-debug.apk and app-release files to the folder VS is looking in:
I placed copy_android_apk.js under [project]\scripts\
[project]\scripts\copy_android_apk.js
I added an "after_build" hook element in [project]\config.xml
<platform name="android">
<hook src="scripts/copy_android_apk.js" type="after_build" />
</platform>
contents of copy_android_apk.js:
#!/usr/bin/env node
module.exports = function (context) {
console.log(" -- manual step -- have to copy apk to this folder because that is where VS is looking for it...");
var fs = require('fs');
var path = require('path');
var rootdir = process.argv[2];
var srcfile = path.join(process.cwd(), "platforms\\android\\app\\build\\outputs\\apk\\debug\\app-debug.apk");
var destfile = path.join(process.cwd(), "platforms\\android\\build\\outputs\\apk\\app-debug.apk");
var destdir = path.dirname(destfile);
//Create the output directory if it doesn't exist
if (!fs.existsSync(destdir)) {
mkdirSyncRecursive(destdir);
}
if (fs.existsSync(srcfile) && fs.existsSync(destdir)) {
fs.createReadStream(srcfile).pipe(
fs.createWriteStream(destfile));
}
srcfile = path.join(process.cwd(), "platforms\\android\\app\\build\\outputs\\apk\\release\\app-release.apk");
destfile = path.join(process.cwd(), "platforms\\android\\build\\outputs\\apk\\app-release.apk");
destdir = path.dirname(destfile);
if (fs.existsSync(srcfile) && fs.existsSync(destdir)) {
fs.createReadStream(srcfile).pipe(
fs.createWriteStream(destfile));
}
/**
* Splits whole path into segments and checks each segment for existence and recreates directory tree from the bottom.
* If since some segment tree doesn't exist it will be created in series.
* Existing directories will be skipped.
* #param {String} directory
*/
function mkdirSyncRecursive(directory) {
var path = directory.replace(/\\$/, '').split('\\');
for (var i = 1; i <= path.length; i++) {
var segment = path.slice(0, i).join('/');
!fs.existsSync(segment) ? fs.mkdirSync(segment) : null;
}
}
}
I tried something that appears to have worked. I cleared the Cordova Cache, Tools/Options
Tools for Appache Cordova
Cordova Tools
Then I restarted Visual Studio
Now it works and will publish the debug directly to the device.
Although the app launched successfully Visual Studio stopped responding, which I recall also happened once in a while after the initial update to 2017, but seemed to go away. After restarting Visual Studio again, and Deploying the debug to Android Device, it operated properly.

Jenkins hanged when I try to build Unity project

I found Jenkins(windows) hanged when I try to build Unity project for android package.
I'm trying to use Jenkins with Unity plugin and windows bat to build project, after windows exe exported successful, android package exported failed.
The arguemnt when I use Unity plugin is
-batchmode -quit -projectPath "D:\Program Files (x86)\Jenkins\jobs\UnityJenkinsTest\workspace\QBAD" -executeMethod QBADBuildScript.Android -logFile "${WORKSPACE}/Build-Log.txt"
Meanwhile, I try using a windows bat to execute the same command from Jenkins, the result is the same.
"D:\Program Files\Unity\Editor\Unity.exe" -batchmode -quit -projectPath "D:\Program Files (x86)\Jenkins\jobs\UnityJenkinsTest\workspace\QBAD" -executeMethod QBADBuildScript.Android -logFile "${WORKSPACE}/Build-Log.txt"
When the building process went to the some part of build process, it hanged, and the build of jenkins never ended. I check with succeed log, it hanged before entering the part of Android.
(succeed log)
Used Assets, sorted by uncompressed size:
....
AndroidSDKTools: // This line and below never showed when hanging happened.
root : D:/Android/sdk
tools : D:/Android/sdk\tools
platform-tools: D:/Android/sdk\platform-tools
build-tools : D:\Android\sdk\build-tools\23.0.1
On the contrary, when I call the same script from command console of windows, it ended and succeed. I wonder what went wrong. Maybe I need set up environment variable for Jenkins.
The version of my Jenkins is 1.614, the version of my Unity is 5.0.1 .
Thanks
public static class AndroidSDKFolder
{
public static string Path
{
get { return EditorPrefs.GetString("AndroidSdkRoot"); }
set { EditorPrefs.SetString("AndroidSdkRoot", value); }
}
}
http://answers.unity3d.com/questions/495735/setting-android-sdk-path-in-environment-variable.html <-- This should help, setting the android sdk path stops the hang.

Unity command line arguments for android and iOS

Please pardon my ignorance, relatively new to working with Unity3D. I am working on automating Unity3d builds from the command line.
I am looking for command line arguments to build apk & xcode project.
Unity's documentation does mention arguments to build a standalone Mac OSX player (-buildOSXPlayer) and a standalone Windows player (-buildWindowsPlayer) but not for android and iOS.
Any help would be really appreciated. Thanks.
Start with Unity's own documentation for command line builds for iOS and android.
For example, put this script in your Assets/Editor folder:
// C# example
using UnityEditor;
class Autobuilder
{
[MenuItem ("File/AutoBuilder/iOS")]
static void PerformBuild ()
{
string[] scenes = { "Assets/MyScene.unity" };
string buildPath = "../../../Build/iOS";
// Create build folder if not yet exists
Directory.CreateDirectory(buildPath);
BuildPipeline.BuildPlayer(scenes, buildPath, BuildTarget.iOS, BuildOptions.Development);
}
}
You can actually run this script in the Unity application by going to File -> Autobuilder -> iOS
To run on command line, it looks something like this:
/Applications/Unity/Unity.app/Contents/MacOS/Unity -quit -batchmode -executeMethod Autobuilder.PerformBuild -email me#email.com -password myPassword
Of course, you're going to want to check the debug log for any errors:
Mac OS X ~/Library/Logs/Unity/Editor.log
Windows XP C:\Documents and Settings\username\Local Settings\Application Data_\Unity\Editor\Editor.log
Windows Vista/7 C:\Users\username\AppData\Local\Unity\Editor\Editor.log
The -executeMethod command line parameter is a very simple option to invoke any function in any of your scripts - which you can then use to do pretty much anything, including firing off an Android build.

Eclipse: Conversion to Dalvik format failed with error 1

This happens instantly when I make a new project in Eclipse.
I only have 1 jar file in the project, I have tried to remove it, and add it again, several times, and cleaned the project after this.
I have updated ProGuard (I think), downloaded the new version, and replaced the lib folder as the threads on here said.
My default.properties file looks like this:
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-8
So can't comment anything about ProGuard which was also mentioned in another thread.
I feel I have tried everything, and still this bug.
One thing I have noticed though if I go to:
window -> preferences -> android -> build. And uncheck "Force error when external jars contain native libraries". Then I get: "Can't resolve R" instead of the Dalvik error.
There is no import named android.R either.
Anyone with some help please?
This doesn't look like the issue with proguard, since it's not even enabled in your defaults.properties file. Try the following:
Uncheck "Force error when external jars contain native libraries" option (just as you did)
Select "Project -> Clean…" from the menu
If that won't help ensure you have the correct R class imported. As stated at source.android.com:
Eclipse sometimes likes to add an import android.R statement at the
top of your files that use resources, especially when you ask eclipse
to sort or otherwise manage imports. This will cause your make to
break. Look out for these erroneous import statements and delete them.
UPDATE
Have a look also at this thread: "Conversion to Dalvik format failed with error 1" on external JAR.
Check the following answers (link will bring you directly to the answer):
michel's answer
user408841's answer
Mido's answer
Joe's Apps' answer
I had mistakenly added a reference to a copy of android.jar, which was not required as it is an android dependency, I removed this and the error went away.
I started having this problem as well... The only thing that fixed it for me was manually downlaoding the newest version of ProGuard (currently 4.6) and replacing the SDK's version of Proguard's bin and lib folders with the newest verison.
After that everything started working again. This is apparently a logged bug...
http://code.google.com/p/android/issues/detail?id=18359
Do you have the new Android SDK? If you do, you have to download the proguard.jar from the proguard website and replace it on the SDK directory.
I just was fighting with this problem myself what I ended up doing is editing the proguard.bat file and the problem vanished
it's in: [Android SDK Installation Directory]\tools\proguard\bin\proguard.bat
Change
call %java_exe% -jar "%PROGUARD_HOME%"\lib\proguard.jar %*
to
call %java_exe% -jar "%PROGUARD_HOME%"\lib\proguard.jar %1 %2 %3 %4 %5 %6 %7 %8 %9
I tried tons of other stuff but this is what did it for me.
You have to clean your project every time if you use CVS update.
I have had this problem occasionally and the fix for me is to switch off 'Build Automatically'. In my experience, Eclipse sometimes gets confused when building apks when automatic building is switched on.
If none of the solutions work for you try to do the following:
Stop looking for online help.
Turn to your project. It can be something in the code that Dalvik interprets in wrong way even if there are no reported errors during the run of application.
I had such a problem. Multiple runs/builds/exports of application with Proguard disabled were successful and only after enabling Proguard an error 1 appeared.
Following steps can help you to resolve the problem:
Create a new project.
In order to detect the suspicious class, begin adding your classes one by one every time running the export signed application tool.
Narrow the search in that class by adding blocks of code to it also one by one.
In my case the error was caused by:
float[][] array1 = null, array2;
for(int i = 0; i < someVal; i++){
if(array1 == null){
array1 = new float[row][col];
}
else{
array2 = new float[array1.length][array1[0].length]; // ERROR 1
// it was assumed that array1 is still null
}
}
When I replaced it with:
float[][] array1 = new float[1][1], array2;
for(int i = 0; i < someVal; i++){
if(i == 0){
array1 = new float[row][col];
}
else{
array2 = new float[array1.length][array1[0].length]; // ERROR 1
// it was assumed that array1 is still null
}
}
the ERROR 1 disappeared.
I've tried many solutions on stackoverflow but nothing worked for me.
I just open the project.properties file in project folder and appcompat library was added twice here like
android.library.reference.1=../appcompat_v7
android.library.reference.1=../appcompat_v7
I just removed one line and this worked for me :)

Categories

Resources