Debian Codegraph @

tools/build-tool/code/toolandroid.pas

raw
1 {
2 Copyright 2014-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Compiling, packaging, installing, running on Android. }
17 unit ToolAndroid;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses Classes,
24 CastleUtils, CastleStringUtils,
25 ToolArchitectures, ToolCompile, ToolPackageFormat, ToolProject,
26 ToolManifest;
27
28 { Compile (for all possible Android CPUs) Android unit or library.
29 When Project <> nil, we assume we compile libraries (one or more .so files),
30 and their final names must match Project.AndroidLibraryFile(CPU) for each CPU.
31
32 CompilerOptions.OS andCompilerOptions.CPU are ignored by this routine.
33 This routine may modify CompilerOptions contents. }
34 procedure CompileAndroid(const Compiler: TCompiler;
35 const Project: TCastleProject;
36 const WorkingDirectory, CompileFile: string;
37 const CompilerOptions: TCompilerOptions);
38
39 { Android CPU values supported by the current compiler. }
40 function DetectAndroidCPUS: TCPUS;
41
42 { Convert CPU to an architecture name understood by Android,
43 see TARGET_ARCH_ABI at https://developer.android.com/ndk/guides/android_mk . }
44 function CPUToAndroidArchitecture(const CPU: TCPU): String;
45
46 procedure PackageAndroid(const Project: TCastleProject;
47 const OS: TOS; const CPUS: TCPUS; const SuggestedPackageMode: TCompilationMode;
48 const PackageFormat: TPackageFormatNoDefault; const PackageNameIncludeVersion: Boolean);
49
50 procedure InstallAndroid(const Project: TCastleProject;
51 const PackageMode: TCompilationMode;
52 const PackageFormat: TPackageFormatNoDefault; const PackageNameIncludeVersion: Boolean);
53
54 procedure RunAndroid(const Project: TCastleProject);
55
56 implementation
57
58 uses SysUtils, DOM, XMLWrite,
59 CastleUriUtils, CastleXmlUtils, CastleLog, CastleFilesUtils, CastleImages,
60 CastleInternalTools,
61 ToolEmbeddedImages, ToolFPCVersion, ToolCommonUtils, ToolUtils,
62 ToolServicesOperations;
63
64 var
65 DetectAndroidCPUSCached: TCPUS;
66
67 function DetectAndroidCPUS: TCPUS;
68 begin
69 if DetectAndroidCPUSCached = [] then
70 begin
71 DetectAndroidCPUSCached := [Arm];
72 if FPCVersion.AtLeast(3, 2, 0) then
73 Include(DetectAndroidCPUSCached, Aarch64)
74 else
75 WritelnWarning('FPC version ' + FPCVersion.ToString + ' does not support compiling for 64-bit Android (Aarch64). Resulting APK will only support 32-bit Android devices.');
76 end;
77 Result := DetectAndroidCPUSCached;
78 end;
79
80 procedure CompileAndroid(const Compiler: TCompiler;
81 const Project: TCastleProject;
82 const WorkingDirectory, CompileFile: string;
83 const CompilerOptions: TCompilerOptions);
84 var
85 CPU: TCPU;
86 begin
87 for CPU in DetectAndroidCPUS do
88 begin
89 CompilerOptions.OS := Android;
90 CompilerOptions.CPU := CPU;
91 Compile(Compiler, WorkingDirectory, CompileFile, CompilerOptions);
92 if Project <> nil then
93 begin
94 CheckRenameFile(Project.AndroidLibraryFile(cpuNone), Project.AndroidLibraryFile(CPU));
95 Writeln('Compiled library for Android in ', Project.AndroidLibraryFile(CPU, false));
96 end;
97 end;
98 end;
99
100 const
101 PackageModeToName: array [TCompilationMode] of string = (
102 'release',
103 'release' { no valgrind support for Android },
104 'debug');
105
106 function CPUToAndroidArchitecture(const CPU: TCPU): String;
107 begin
108 case CPU of
109 { The armeabi-v7a is our proper platform, with hard floats.
110 See https://developer.android.com/ndk/guides/application_mk.html
111 and http://stackoverflow.com/questions/24948008/linking-so-file-within-android-ndk
112 and *do not* confuse this with (removed now) armeabi-v7a-hard ABI:
113 https://android.googlesource.com/platform/ndk/+show/353e653824b79c43b948429870d0abeedebde386/docs/HardFloatAbi.md
114 }
115 arm : Result := 'armeabi-v7a';
116 aarch64: Result := 'arm64-v8a';
117 i386 : Result := 'x86';
118 x86_64 : Result := 'x86_64';
119 else raise Exception.CreateFmt('Android does not support CPU "%s"', [CPUToString(CPU)]);
120 end;
121 end;
122
123 function Capitalize(const S: string): string;
124 begin
125 Result := S;
126 if Result <> '' then
127 Result := AnsiUpperCase(Result[1]) + SEnding(Result, 2);
128 end;
129
130 { Try to find ExeName executable.
131 If not found -> exception (if Required) or return '' (if not Required). }
132 function FinishExeSearch(const ExeName, BundleName, EnvVarName: string;
133 const Required: boolean): string;
134 begin
135 { try to find on $PATH }
136 Result := FindExe(ExeName);
137 { fail if still not found }
138 if Required and (Result = '') then
139 raise Exception.Create('Cannot find "' + ExeName + '" executable on $PATH, or within $' + EnvVarName + '. Install Android ' + BundleName + ' and make sure that "' + ExeName + '" executable is on $PATH, or that $' + EnvVarName + ' environment variable is set correctly.');
140 end;
141
142 { Try to find "adb" tool executable.
143 If not found -> exception (if Required) or return '' (if not Required). }
144 function AdbExe(const Required: boolean = true): string;
145 const
146 ExeName = 'adb';
147 BundleName = 'SDK';
148 EnvVarName1 = 'ANDROID_HOME';
149 EnvVarName2 = 'ANDROID_SDK_ROOT';
150 var
151 Env: string;
152 begin
153 Result := '';
154 { Try to find in $ANDROID_SDK_ROOT or $ANDROID_HOME.
155 Note: For a while, ANDROID_HOME for deprecated and ANDROID_SDK_ROOT
156 recommended.
157 Then, ANDROID_SDK_ROOT was deprecated and now ANDROID_HOME is recommended.
158 See
159 - official docs:
160 https://developer.android.com/tools/variables?hl=en
161 https://developer.android.com/tools?hl=en
162 - other software also adjusting:
163 https://github.com/apache/cordova-android/issues/1425
164 https://github.com/bazelbuild/bazel/issues/13612
165 }
166 Env := GetEnvironmentVariable(EnvVarName1);
167 if Env = '' then
168 GetEnvironmentVariable(EnvVarName2);
169 if Env <> '' then
170 begin
171 Result := AddExeExtension(InclPathDelim(Env) + 'platform-tools' + PathDelim + ExeName);
172 if not RegularFileExists(Result) then
173 Result := '';
174 end;
175 { try to find on $PATH }
176 if Result = '' then
177 Result := FinishExeSearch(ExeName, BundleName, EnvVarName1, Required);
178 end;
179
180 { Filename (without any leading path) of the Android output (APK, AAB) file. }
181 function AndroidPackageFile(const Project: TCastleProject;
182 const Mode: TCompilationMode;
183 const PackageFormat: TPackageFormatNoDefault;
184 const PackageNameIncludeVersion: Boolean): String;
185 begin
186 Result := Project.Name;
187 if PackageNameIncludeVersion and (Project.Version.DisplayValue <> '') then
188 Result += '-' + Project.Version.DisplayValue;
189 Result += '-android' + '-' + PackageModeToName[Mode];
190 case PackageFormat of
191 pfAndroidApk:
192 Result += '.apk';
193 pfAndroidAppBundle:
194 Result += '.aab';
195 else
196 raise Exception.Create('Unexpected PackageFormat in for Android: ' + PackageFormatToString(PackageFormat));
197 end;
198 end;
199
200 procedure PackageAndroid(const Project: TCastleProject;
201 const OS: TOS; const CPUS: TCPUS; const SuggestedPackageMode: TCompilationMode;
202 const PackageFormat: TPackageFormatNoDefault; const PackageNameIncludeVersion: Boolean);
203 var
204 AndroidProjectPath: string;
205
206 { Some utility procedures PackageXxx below.
207 They work just like Xxx, but target filename should not contain
208 prefix AndroidProjectPath. They avoid overwriting stuff
209 already existing (in case multiple services
210 contain the same path inside), but warn about it. }
211
212 procedure PackageCheckForceDirectories(const Dirs: string);
213 begin
214 CheckForceDirectories(AndroidProjectPath + Dirs);
215 end;
216
217 procedure PackageSaveImage(const Image: TCastleImage; const FileName: string);
218 begin
219 PackageCheckForceDirectories(ExtractFilePath(FileName));
220 if not RegularFileExists(AndroidProjectPath + FileName) then
221 SaveImage(Image, FilenameToUriSafe(AndroidProjectPath + FileName))
222 else
223 WritelnWarning('Android', 'Android package file specified by multiple services: ' + FileName);
224 end;
225
226 procedure PackageSmartCopyFile(const FileFrom, FileTo: string);
227 begin
228 PackageCheckForceDirectories(ExtractFilePath(FileTo));
229 if not RegularFileExists(AndroidProjectPath + FileTo) then
230 SmartCopyFile(FileFrom, AndroidProjectPath + FileTo)
231 else
232 WritelnWarning('Android', 'Android package file specified by multiple services: ' + FileTo);
233 end;
234
235 {
236 procedure PackageStringToFile(const FileTo, Contents: string);
237 begin
238 if not RegularFileExists(AndroidProjectPath + FileTo) then
239 begin
240 PackageCheckForceDirectories(ExtractFilePath(FileTo));
241 StringToFile(FileTo, Contents);
242 end else
243 WritelnWarning('Android package file specified by multiple services: ' + FileTo);
244 end;
245 }
246
247 { Generate files for Android project from templates. }
248 procedure GenerateFromTemplates;
249 var
250 TemplatePath: string;
251 begin
252 { Add Android project core directory.
253 We used to have a choice here (base or integrated),
254 but now it's always integrated. }
255 TemplatePath := 'android/integrated/';
256 Project.ExtractTemplate(TemplatePath, AndroidProjectPath);
257 end;
258
259 { Generate files for Android project from templates, adding services. }
260 procedure GenerateServicesFromTemplates;
261
262 procedure ExtractService(const ServiceName: string);
263 var
264 TemplatePath: string;
265 begin
266 TemplatePath := 'android/integrated-services/' + ServiceName;
267 Project.ExtractTemplate(TemplatePath, AndroidProjectPath);
268 end;
269
270 var
271 I: Integer;
272 begin
273 { add declared services }
274 for I := 0 to Project.AndroidServices.Count - 1 do
275 ExtractService(Project.AndroidServices[I].Name);
276
277 { add automatic services }
278 if (depSound in Project.Dependencies) and
279 not Project.AndroidServices.HasService('sound') then
280 ExtractService('sound');
281 if (depOggVorbis in Project.Dependencies) and
282 not Project.AndroidServices.HasService('ogg_vorbis') then
283 ExtractService('ogg_vorbis');
284 if (depFreeType in Project.Dependencies) and
285 not Project.AndroidServices.HasService('freetype') then
286 ExtractService('freetype');
287 if (depPng in Project.Dependencies) and
288 not Project.AndroidServices.HasService('png') then
289 ExtractService('png');
290 if (depHttps in Project.Dependencies) and
291 not Project.AndroidServices.HasService('download_urls') then
292 ExtractService('download_urls');
293 end;
294
295 procedure GenerateIcons;
296 var
297 Icon: TCastleImage;
298
299 procedure SaveResized(const Size: Integer; const S: string);
300 var
301 R: TCastleImage;
302 Dir: string;
303 begin
304 R := Icon.MakeResized(Size, Size, BestInterpolation);
305 try
306 Dir := 'app' + PathDelim + 'src' + PathDelim + 'main' + PathDelim +
307 'res' + PathDelim + 'mipmap-' + S + 'dpi';
308 PackageSaveImage(R, Dir + PathDelim + 'ic_launcher.png');
309 finally FreeAndNil(R) end;
310 end;
311
312 begin
313 Icon := Project.Icons.FindReadable;
314 if Icon = nil then
315 begin
316 WritelnWarning('Icon', 'No icon in a format readable by our engine (for example, png or jpg) is specified in CastleEngineManifest.xml. Using default icon.');
317 Icon := DefaultIcon;
318 end;
319 try
320 SaveResized(48, 'm');
321 SaveResized(72, 'h');
322 SaveResized(96, 'xh');
323 SaveResized(144, 'xxh');
324 finally
325 if Icon = DefaultIcon then
326 Icon := nil else
327 FreeAndNil(Icon);
328 end;
329 end;
330
331 procedure GenerateAssets;
332 begin
333 Project.CopyData(AndroidProjectPath +
334 'app' + PathDelim +
335 'src' + PathDelim +
336 'main' + PathDelim +
337 'assets',
338 cpAndroid);
339 end;
340
341 procedure GenerateLocalization;
342 var
343 LocalizedAppName: TLocalizedAppName;
344 Doc: TXMLDocument;
345 RootNode, StringNode: TDOMNode;
346 I: TXMLElementIterator;
347 Language, StringsPath: String;
348 begin
349 if not Assigned(Project.LocalizedAppNames) then Exit;
350
351 //Change default app_name to translatable:
352 StringsPath := AndroidProjectPath + 'app' + PathDelim +'src' + PathDelim + 'main' + PathDelim + 'res' + PathDelim + 'values' + PathDelim + 'strings.xml';
353 URLReadXML(Doc, StringsPath);
354 try
355 I := Doc.DocumentElement.ChildrenIterator;
356 try
357 while I.GetNext do
358 if (I.Current.TagName = 'string') and (I.Current.AttributeString('name') = 'app_name') then
359 begin
360 I.Current.AttributeSet('translatable', 'true');
361 Break; //There can only be one string 'app_name', so we don't need to continue the loop.
362 end;
363 finally
364 I.Free;
365 end;
366
367 WriteXMLFile(Doc, StringsPath);
368 finally
369 Doc.Free;
370 end;
371
372 //Write strings for every chosen language:
373 for LocalizedAppName in Project.LocalizedAppNames do
374 begin
375 Doc := TXMLDocument.Create;
376 try
377 RootNode := Doc.CreateElement('resources');
378 Doc.Appendchild(RootNode);
379 RootNode:= Doc.DocumentElement;
380
381 StringNode := Doc.CreateElement('string');
382 TDOMElement(StringNode).AttributeSet('name', 'app_name');
383 StringNode.AppendChild(Doc.CreateTextNode(UTF8Decode(LocalizedAppName.AppName)));
384 RootNode.AppendChild(StringNode);
385
386 if LocalizedAppName.Language = 'default' then
387 Language := ''
388 else
389 Language := '-' + LocalizedAppName.Language;
390
391 StringsPath := AndroidProjectPath + 'app' + PathDelim +'src' + PathDelim + 'main' + PathDelim + 'res' + PathDelim +
392 'values' + Language + PathDelim + 'strings.xml';
393
394 CheckForceDirectories(ExtractFilePath(StringsPath));
395 WriteXMLFile(Doc, StringsPath);
396 finally
397 Doc.Free;
398 end;
399 end;
400 end;
401
402 procedure GenerateLibrary;
403 var
404 CPU: TCPU;
405 JniPath, LibraryWithoutCPU, LibraryFileName: String;
406 begin
407 JniPath := 'app' + PathDelim + 'src' + PathDelim + 'main' + PathDelim +
408 { Place precompiled libs in jniLibs/ .
409 This is where precompiled native libs should be, according to
410 https://developer.android.com/studio/projects/gradle-external-native-builds . }
411 'jniLibs' + PathDelim;
412 LibraryWithoutCPU := ExtractFileName(Project.AndroidLibraryFile(cpuNone));
413
414 for CPU in CPUS do
415 begin
416 LibraryFileName := Project.AndroidLibraryFile(CPU);
417 PackageSmartCopyFile(LibraryFileName,
418 JniPath + CPUToAndroidArchitecture(CPU) + PathDelim + LibraryWithoutCPU);
419 end;
420 end;
421
422 var
423 KeyStore, KeyAlias, KeyStorePassword, KeyAliasPassword: string;
424
425 procedure CalculateSigningProperties(var PackageMode: TCompilationMode);
426 const
427 SigningPropertiesFile = 'AndroidSigningProperties.txt';
428 WWW = 'https://castle-engine.io/android_faq#_signing_a_release_apk_aab';
429 MissingSigningSuffix =
430 ' See ' + WWW + ' for documentation how to create and use keys to sign release Android APK / AAB.' + NL +
431 ' Falling back to creating debug apk.';
432 MissingSigningInfo =
433 'Key information (key.store, key.alias, key.store.password, key.alias.password) to sign release Android package not found inside "' + SigningPropertiesFile + '" file.' + NL +
434 MissingSigningSuffix;
435 MissingSigningFile =
436 'Information about the keys to sign release Android package not found, because "' + SigningPropertiesFile + '" file does not exist.' + NL +
437 MissingSigningSuffix;
438
439 procedure LoadSigningProperties(const FileName: string);
440 var
441 S: TStringList;
442 begin
443 S := TStringList.Create;
444 try
445 S.LoadFromFile(FileName);
446 if (PackageMode <> cmDebug) and (
447 (S.IndexOfName('key.store') = -1) or
448 (S.IndexOfName('key.alias') = -1) or
449 (S.IndexOfName('key.store.password') = -1) or
450 (S.IndexOfName('key.alias.password') = -1)) then
451 begin
452 WritelnWarning('Android', MissingSigningInfo);
453 PackageMode := cmDebug;
454 end;
455 if PackageMode <> cmDebug then
456 begin
457 KeyStore := S.Values['key.store'];
458 KeyAlias := S.Values['key.alias'];
459 KeyStorePassword := S.Values['key.store.password'];
460 KeyAliasPassword := S.Values['key.alias.password'];
461
462 (*
463 Project.AndroidSigningConfig :=
464 'signingConfigs {' + NL +
465 ' release {' + NL +
466 ' storeFile file("' + KeyStore + '")' + NL +
467 ' storePassword "' + KeyStorePassword + '"' + NL +
468 ' keyAlias "' + KeyAlias + '"' + NL +
469 ' keyPassword "' + KeyAliasPassword + '"' + NL +
470 ' }' + NL +
471 '}' + NL;
472 Project.AndroidSigningConfigDeclare := 'signingConfig signingConfigs.release';
473
474 This fails with gradle error
475 (as of 'com.android.tools.build:gradle-experimental:0.7.0' ; did not try with later versions)
476
477 * Where:
478 Build file '/tmp/castle-engine157085/app/build.gradle' line: 26
479 * What went wrong:
480 A problem occurred configuring project ':app'.
481 > Exception thrown while executing model rule: android { ... } @ app/build.gradle line 4, column 5 > named(release)
482 > Attempt to read a write only view of model of type 'org.gradle.model.ModelMap<com.android.build.gradle.managed.BuildType>' given to rule 'android { ... } @ app/build.gradle line 4, column 5'
483
484 See
485 https://code.google.com/p/android/issues/detail?id=182249
486 http://stackoverflow.com/questions/32109501/adding-release-keys-in-the-experimental-gradle-plugin-for-android
487
488 We use simpler solution now, from the bottom of
489 https://plus.googleapis.com/+JoakimEngstr%C3%B6mJ/posts/NY3JUkz5dPP
490 See also
491 http://www.tinmith.net/wayne/blog/2014/08/gradle-sign-command-line.htm
492 *)
493 end;
494 finally FreeAndNil(S) end;
495 end;
496
497 begin
498 KeyStore := '';
499 KeyAlias := '';
500 KeyStorePassword := '';
501 KeyAliasPassword := '';
502 if RegularFileExists(Project.Path + SigningPropertiesFile) then
503 begin
504 LoadSigningProperties(Project.Path + SigningPropertiesFile);
505 end else
506 if PackageMode <> cmDebug then
507 begin
508 WritelnWarning('Android', MissingSigningFile);
509 PackageMode := cmDebug;
510 end;
511 end;
512
513 { Run Gradle to actually build the final apk. }
514 procedure RunGradle(const PackageMode: TCompilationMode);
515 var
516 Args: TCastleStringList;
517 begin
518 Args := TCastleStringList.Create;
519 try
520 case PackageFormat of
521 pfAndroidApk:
522 Args.Add('assemble' + Capitalize(PackageModeToName[PackageMode]));
523 pfAndroidAppBundle:
524 Args.Add(':app:bundle' + Capitalize(PackageModeToName[PackageMode]));
525 else
526 raise Exception.Create('Unexpected PackageFormat in PackageAndroid: ' + PackageFormatToString(PackageFormat));
527 end;
528 if not Verbose then
529 Args.Add('--quiet');
530 if PackageMode <> cmDebug then
531 begin
532 Args.Add('-Pandroid.injected.signing.store.file=' + KeyStore);
533 Args.Add('-Pandroid.injected.signing.store.password=' + KeyStorePassword);
534 Args.Add('-Pandroid.injected.signing.key.alias=' + KeyAlias);
535 Args.Add('-Pandroid.injected.signing.key.password=' + KeyAliasPassword);
536 end;
537
538 {$ifdef MSWINDOWS}
539 RunCommandSimple(AndroidProjectPath, AndroidProjectPath + 'gradlew.bat', Args.ToArray);
540 {$else}
541 if RegularFileExists(AndroidProjectPath + 'gradlew') then
542 begin
543 Args.Insert(0, './gradlew');
544 RunCommandSimple(AndroidProjectPath, 'bash', Args.ToArray);
545 end else
546 begin
547 Writeln('Local Gradle wrapper ("gradlew") not found, so we will call the Gradle on $PATH.');
548 Writeln('Make sure you have installed Gradle (e.g. from the Debian "gradle" package), in a version compatible with the Android Gradle plugin (see https://developer.android.com/studio/releases/gradle-plugin.html#updating-gradle ).');
549 RunCommandSimple(AndroidProjectPath, 'gradle', Args.ToArray);
550 end;
551 {$endif}
552 finally FreeAndNil(Args) end;
553 end;
554
555 var
556 PackageName: string;
557 PackageMode: TCompilationMode;
558 begin
559 { calculate clean AndroidProjectPath }
560 AndroidProjectPath := TempOutputPath(Project.Path) +
561 'android' + PathDelim + 'project' + PathDelim;
562 if DirectoryExists(AndroidProjectPath) then
563 RemoveNonEmptyDir(AndroidProjectPath);
564
565 PackageMode := SuggestedPackageMode;
566
567 CalculateSigningProperties(PackageMode);
568
569 GenerateFromTemplates;
570 GenerateServicesFromTemplates;
571 PackageServices(Project, Project.AndroidServices,
572 'castle-data:/android/integrated-services/', AndroidProjectPath);
573 GenerateIcons;
574 GenerateAssets;
575 GenerateLocalization;
576 GenerateLibrary;
577 RunGradle(PackageMode);
578
579 PackageName := AndroidPackageFile(Project, PackageMode, PackageFormat, PackageNameIncludeVersion);
580 case PackageFormat of
581 pfAndroidApk:
582 begin
583 CheckRenameFile(AndroidProjectPath + 'app' + PathDelim +
584 'build' + PathDelim +
585 'outputs' + PathDelim +
586 'apk' + PathDelim +
587 PackageModeToName[PackageMode] + PathDelim +
588 'app-' + PackageModeToName[PackageMode] + '.apk',
589 Project.OutputPath + PackageName);
590 end;
591 pfAndroidAppBundle:
592 begin
593 CheckRenameFile(AndroidProjectPath + 'app' + PathDelim +
594 'build' + PathDelim +
595 'outputs' + PathDelim +
596 'bundle' + PathDelim +
597 PackageModeToName[PackageMode] + PathDelim +
598 'app-' + PackageModeToName[PackageMode] + '.aab',
599 Project.OutputPath + PackageName);
600 DoMakeExecutable(Project.OutputPath + PackageName);
601 end;
602 else
603 raise Exception.Create('Unexpected PackageFormat in PackageAndroid: ' + PackageFormatToString(PackageFormat));
604 end;
605
606 Writeln('Build ' + PackageName);
607 end;
608
609 procedure InstallAndroid(const Project: TCastleProject;
610 const PackageMode: TCompilationMode;
611 const PackageFormat: TPackageFormatNoDefault; const PackageNameIncludeVersion: Boolean);
612 var
613 PackageName: string;
614 begin
615 PackageName := Project.OutputPath +
616 AndroidPackageFile(Project, PackageMode, PackageFormat, PackageNameIncludeVersion);
617 if not RegularFileExists(PackageName) then
618 raise Exception.CreateFmt('No Android package found: "%s"', [PackageName]);
619
620 { Uninstall and then install, instead of calling "install -r",
621 to avoid failures because apk signed with different keys (debug vs release). }
622
623 Writeln('Reinstalling application identified as "' + Project.QualifiedName + '".');
624 Writeln('If this fails, an often cause is that a previous development version of the application, signed with a different key, remains on the device. In this case uninstall it first (note that it will clear your UserConfig data, unless you use -k) by "adb uninstall ' + Project.QualifiedName + '"');
625 Flush(Output); // don't mix output with adb output
626 RunCommandSimple(AdbExe, ['install', '-r', PackageName]);
627 Writeln('Install successful.');
628 end;
629
630 procedure RunAndroid(const Project: TCastleProject);
631 var
632 ActivityName, LogTag: string;
633 begin
634 ActivityName := 'io.castleengine.MainActivity';
635 RunCommandSimple(AdbExe, ['shell', 'am', 'start',
636 '-a', 'android.intent.action.MAIN',
637 '-n', Project.QualifiedName + '/' + ActivityName ]);
638 Writeln('Android application successfully started.');
639
640 LogTag := Copy(Project.Name, 1, MaxAndroidTagLength);
641
642 Writeln('Running "adb logcat -s ' + LogTag + ':V" (so we assume your ApplicationName is "' + Project.Name + '").');
643 Flush(Output); // flush, otherwise it would not appear before "adb logcat" output
644
645 { Initial implementation run this through ExecuteProcess,
646 because we don't want to capture output,
647 we want to immediately pass it to user.
648
649 Later implementation relies on RunCommandSimple, this way
650 we pass new ChildProcessId to EditorUtils, since it writelns the magic string
651 'Castle Game Engine Internal: ProcessID: ...' . And passing this
652 ChildProcessId to EditorUtils allows better behavior when using "Stop"
653 in CGE editor that runs Android application:
654
655 1. Without it, it seems that killing "castle-engine run" doesn't kill "adb logcat...",
656 it is left running in the background (and wasting resources).
657
658 2. Moreover, actually CGE editor would have wrong ChildProcessId,
659 leftover from previous ADB execution that started the execution.
660 We could introduce a new magic message like
661 'Stopped: Castle Game Engine Internal: ProcessID: ...'
662 but it would not solve issue AD 1 above.
663 }
664 //ExecuteProcess(AdbExe, ['logcat', '-s', LogTag + ':V']);
665 RunCommandSimple(AdbExe, ['logcat', '-s', LogTag + ':V']);
666 end;
667
668 end.