### Android Project File Example (.csproj) Source: https://github.com/dotnet/android/wiki/Migrating-Xamarin.Android-Applications-to-.NET-6 An example of an SDK-style .csproj file for a .NET 6 Android application. This format is standard for modern .NET projects and replaces older formats like `packages.config` for NuGet management. ```dotnet net6.0-android MyAndroidApp com.mycompany.myandroidapp 1 1.0 21 ``` -------------------------------- ### Release Notes Structure Example Source: https://github.com/dotnet/android/blob/main/Documentation/release-notes/README.md An example of how to structure release notes, including a section for deprecations, removals, and default configuration changes, with a specific example for the XA1023 warning. ```markdown #### Deprecations, removals, and default configuration changes - [XA1023 warning for upcoming DX DEX compiler deprecation](#xa1023-warning-for-upcoming-dx-dex-compiler-deprecation) ### XA1023 warning for upcoming DX DEX compiler deprecation Projects that have **Dex compiler** set to **dx** in the Visual Studio project property pages will now get a build warning: ``` warning XA1023: Using the DX DEX Compiler is deprecated. Please update `$(AndroidDexTool)` to `d8`. ``` To resolve this warning, set the **Dex compiler** in the Visual Studio project property pages to **d8** or edit the project file [in Visual Studio][edit-project-files] or another text editor and set the `AndroidDexTool` MSBuild property to `d8`: ```xml d8 ``` [edit-project-files]: https://docs.microsoft.com/visualstudio/msbuild/visual-studio-integration-msbuild?view=vs-2019#edit-project-files-in-visual-studio #### Background information Google [has deprecated the DX DEX compiler][dx-deprecation] in favor of the [D8 DEX compiler][d8-upstream]. After February 1, 2021, DX will no longer be a part of the Android SDK or Android Studio. Project authors are encouraged to migrate their projects to D8 at their earliest convenience to prepare for this change. [dx-deprecation]: https://android-developers.googleblog.com/2020/02/the-path-to-dx-deprecation.html [d8-upstream]: https://developer.android.com/studio/releases/gradle-plugin#D8 ``` -------------------------------- ### Install NativeAOT Sample Source: https://github.com/dotnet/android/blob/main/samples/NativeAOT/README.md Installs the NativeAOT sample application on Android using MSBuild. This command utilizes the 'Install' target to build and deploy the specified project. ```shell dotnet-local.sh build samples/NativeAOT/NativeAOT.csproj -c Debug -t:Install -tl:off ``` -------------------------------- ### VSCode Build Commands for .NET for Android Source: https://github.com/dotnet/android/blob/main/Documentation/guides/vscode-support.md Example build commands available through the VSCode Build Command Pallette for .NET for Android development. These commands cover dependency installation, building, and packaging. ```bash Prepare PrepareExternal Build Pack Everything ``` -------------------------------- ### Create Installers Source: https://github.com/dotnet/android/blob/main/Documentation/building/unix/instructions.md Builds installers for macOS (.pkg), Windows (.vsix), and .NET for Android workload .nupkg files after a successful build. ```makefile make create-installers ``` -------------------------------- ### Install .NET Global Tools Source: https://github.com/dotnet/android/blob/main/Documentation/guides/tracing.md Installs the necessary .NET global tools for tracing Android applications, including dotnet-trace, dotnet-dsrouter, and dotnet-gcdump. It also shows how to install prerelease versions. ```sh $ dotnet tool install -g dotnet-trace You can invoke the tool using the following command: dotnet-trace Tool 'dotnet-trace' was successfully installed. $ dotnet tool install -g dotnet-dsrouter You can invoke the tool using the following command: dotnet-dsrouter Tool 'dotnet-dsrouter' was successfully installed. $ dotnet tool install -g dotnet-gcdump You can invoke the tool using the following command: dotnet-gcdump Tool 'dotnet-gcdump' was successfully installed. ``` ```sh $ dotnet tool install -g dotnet-trace --add-source=https://aka.ms/dotnet-tools/index.json --prerelease You can invoke the tool using the following command: dotnet-trace Tool 'dotnet-trace' was successfully installed. ``` -------------------------------- ### Mono Profiling Output Example Source: https://github.com/dotnet/android/blob/main/Documentation/guides/profiling.md An example of the output generated by mprof-report, showing profiling statistics such as JIT summary, GC summary, and method call summary with timings and call counts. ```csharp Mono log profiler data Profiler version: 3.0 Data version: 17 Arguments: log:calls,output=/data/user/0/com.xamarin.android.helloworld/files/.__override__/profile.mlpd Architecture: armv8 Operating system: linux Mean timer overhead: 47 nanoseconds Program startup: Wed Sep 4 10:46:50 2019 Program ID: 11929 Server listening on: 44657 JIT summary Compiled methods: 1454 Generated code size: 459916 JIT helpers: 0 JIT helpers code size: 0 GC summary GC resizes: 0 Max heap size: 0 Object moves: 0 Method call summary Total(ms) Self(ms) Calls Method name 465 0 1 (wrapper runtime-invoke) :runtime_invoke_void_JnienvInitializeArgs* (object,intptr,intptr,intptr) 465 9 1 Android.Runtime.JNIEnv:Initialize (Android.Runtime.JnienvInitializeArgs*) 171 0 3 (wrapper native-to-managed) Android.Runtime.DynamicMethodNameCounter:3 (intptr,intptr,intptr) 171 0 3 (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter:3 (intptr,intptr,intptr) 170 2 3 Android.App.Activity:n_OnCreate_Landroid_os_Bundle_ (intptr,intptr,intptr) 162 6 1 Android.Runtime.AndroidRuntime:.ctor (intptr,intptr,bool,intptr,intptr) 153 2 3 HelloWorld.MainActivity:OnCreate (Android.OS.Bundle) 147 0 21 (wrapper runtime-invoke) object:runtime_invoke_void (object,intptr,intptr,intptr) 132 1 14 Java.Interop.JniPeerMembers:.ctor (string,System.Type) 124 0 8 (wrapper runtime-invoke) object:runtime_invoke_void (object,intptr,intptr,intptr) 117 7 1 Java.Interop.JniRuntime:.ctor (Java.Interop.JniRuntime/CreationOptions) 106 6 14 Java.Interop.JniPeerMembers:.ctor (string,System.Type,bool,bool) 105 0 57 Java.Interop.JniRuntime/JniTypeManager:GetTypeSignature (System.Type) 100 0 4 (wrapper runtime-invoke) :runtime_invoke_void_intptr_int_intptr_intptr_int (object,intptr,intptr,intptr) 100 2 4 Android.Runtime.JNIEnv:RegisterJniNatives (intptr,int,intptr,intptr,int) 99 1 57 System.Linq.Enumerable:FirstOrDefault (System.Collections.Generic.IEnumerable`1) 99 0 10 Java.Interop.JniEnvironment/InstanceMethods:CallNonvirtualVoidMethod (Java.Interop.JniObjectReference,Java.Interop.JniObjectReference,Java.Interop.JniMethodInfo,Java.Interop.JniArgumentValue*) 98 5 57 System.Linq.Enumerable:TryGetFirst (System.Collections.Generic.IEnumerable`1,bool&) ``` -------------------------------- ### Install Android SDK Components using sdkmanager Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/getting-started/installation/dependencies.md This command utilizes the `sdkmanager` tool to manually install specific Android SDK components, including platforms, platform-tools, build-tools, emulator images, and command-line tools. It requires specifying the SDK root directory and accepting licenses. This method provides granular control over which components are installed. ```console sdkmanager "platforms;android-34" "platform-tools" "build-tools;34.0.0" "emulator" "system-images;android-34;default;x86_64" "cmdline-tools;11.0" --sdk_root=c:\android-sdk ``` -------------------------------- ### Minimal, Complete, and Verifiable Example Source: https://github.com/dotnet/android/wiki/Submitting-Bugs,-Feature-Requests,-and-Pull-Requests Guidance on creating a minimal, complete, and verifiable example to demonstrate a bug, as per Stack Overflow best practices. ```markdown Create a [minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve) to demonstrate the problem. ``` -------------------------------- ### Running and Verifying an Android Application on a Device Source: https://github.com/dotnet/android/blob/main/Documentation/workflow/UnitTests.md This C# code snippet demonstrates how to build, install, and run a Xamarin.Android application on a target device. It includes steps to set the default target device using an environment variable, install the APK, run the application, and wait for a specific activity to start by monitoring logcat output. ```csharp using System.IO; using NUnit.Framework; using Xamarin.Android.Build.Tests; [Test] public void MyAppShouldRun ([Values (true, false)] bool isRelease) { var proj = new XamarinAndroidApplicationProject () { IsRelease = isRelease, }; proj.SetDefaultTargetDevice (); using (var b = CreateApkBuilder ()) { // Build and Install the app Assert.True (b.Install (proj), "Project should have installed."); // Run it RunProjectAndAssert (proj, b); // Wait for the app to start with a 30 second timeout Assert.True (WaitForActivityToStart (proj.PackageName, "MainActivity", Path.Combine (Root, b.ProjectDirectory, "logcat.log"), 30), "Activity should have started."); } } ``` -------------------------------- ### Install .NET for Android Workload Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/getting-started/installation/net-android.md Installs the .NET Android workload using the .NET CLI. This command is essential for enabling Android development with .NET. Ensure .NET is installed first. ```dotnetcli dotnet workload install android ``` -------------------------------- ### simpleperf Record Command Example Source: https://github.com/dotnet/android/blob/main/Documentation/guides/profiling.md An example of the `simpleperf record` command used to capture profiling data for an Android application. It specifies tracepoint events, output file, event type, sample frequency, call graph collection, duration, symbol file path, and the target app. ```bash simpleperf record --in-app --tracepoint-events /data/local/tmp/tracepoint_events -o perf.data -e task-clock:u -f 1000 -g --duration 10 --symfs /data/local/tmp/native_libs/ --app Xamarin.Forms_Performance_Integration ``` -------------------------------- ### Example Output of jit-times Source: https://github.com/dotnet/android/blob/main/tools/jit-times/README.md An example of the output generated by the `jit-times` tool when processing a `methods.txt` file, showing JIT times for various methods. ```csharp Total (ms) | Self (ms) | Method 8.35 | 8.35 | System.Reflection.Emit.OpCodes:.cctor () 0.57 | 0.57 | System.Reflection.Emit.ILGenerator:Emit (System.Reflection.Emit.OpCode,System.Reflection.Emit.LocalBuilder) 0.49 | 0.49 | System.Reflection.Emit.ILGenerator:Emit (System.Reflection.Emit.OpCode,System.Reflection.MethodInfo) 0.39 | 0.39 | System.Reflection.Emit.DynamicMethod:.ctor (string,System.Reflection.MethodAttributes,System.Reflection.CallingConventions,System.Type,System.Type[],System.Type,System.Reflection.Module,bool,bool) 0.36 | 0.36 | System.Reflection.Emit.ILGenerator:Emit (System.Reflection.Emit.OpCode,System.Reflection.Emit.Label) 0.36 | 0.36 | System.Reflection.Emit.ILGenerator:DeclareLocal (System.Type,bool) 0.35 | 0.35 | System.Reflection.Emit.ILGenerator:BeginExceptionBlock () 0.34 | 0.34 | System.Reflection.Emit.ILGenerator:Emit (System.Reflection.Emit.OpCode,System.Type) 0.31 | 0.31 | System.Reflection.Emit.DynamicMethod:CreateDynMethod () 0.29 | 0.29 | System.Reflection.Emit.ILGenerator:DefineLabel () 0.27 | 0.27 | System.Reflection.Emit.ILGenerator:BeginCatchBlock (System.Type) ... Sum of self time (ms): 16.02 ``` -------------------------------- ### API Compatibility Checks Jenkins Link Example Source: https://github.com/dotnet/android/blob/main/Documentation/workflow/HowToBumpMono.md Example of Jenkins build and API compatibility check links, illustrating where to find reported API breakage. ```text https://jenkins.mono-project.com/job/xamarin-android-pr-builder/4577/ https://jenkins.mono-project.com/job/xamarin-android-pr-builder/4577/API_20Compatibility_20Checks/ ``` -------------------------------- ### ADB0060 Error Message Example Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/messages/adb0060.md This snippet shows an example of the ADB0060 error message, indicating that there is not enough storage space on the device to install a package. ```text error ADB0060: There is not enough storage space on the device to store package: {packageName}. Free up some space and try again. ``` ```text error ADB0060: There is not enough storage space on the device to store package: {packageName}. Free up some space or use an SD card and try again. ``` -------------------------------- ### List Available Android SDK Components Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/getting-started/installation/dependencies.md This command lists all available components that can be installed using the `sdkmanager` tool. This is useful for identifying specific platform versions, build tools, system images, or other SDK components needed for Android development. ```console sdkmanager --list ``` -------------------------------- ### Getting Help for Preparation Utility Parameters Source: https://github.com/dotnet/android/blob/main/build-tools/xaprepare/README.md This command displays a list of all command-line parameters accepted by the preparation utility, providing details on their usage and effects. ```makefile make prepare-help ``` -------------------------------- ### Capturing timing=fast-bare Mode Logs Source: https://github.com/dotnet/android/blob/main/Documentation/workflow/SystemProperties.md A sequence of shell commands to enable fast-bare timing, build and install the app, adjust logcat buffer, clear logs, start the activity, and dump timing data. This is for detailed performance analysis. ```shell # Enable timing log messages $ adb shell setprop debug.mono.log timing=fast-bare # Build and install the application $ dotnet build -t:Install -p:Configuration=Release # Increase logcat buffer size $ adb logcat -G 16M # Clear logcat buffer $ adb logcat -c # Start the activity and wait for startup $ adb shell am start -n PACKAGE_NAME/ACTIVITY_NAME -S -W # Log gathered events to logcat $ adb shell am broadcast -a mono.android.app.DUMP_TIMING_DATA PACKAGE_NAME # Dump logcat contents to a file adb logcat -d > logcat.txt ``` -------------------------------- ### Prepare the Project Source: https://github.com/dotnet/android/blob/main/Documentation/building/unix/instructions.md Ensures build dependencies are installed, updates git submodules, and downloads NuGet dependencies. Can use either `msbuild` or `xbuild`. ```makefile make prepare # -or- make prepare MSBUILD=msbuild ``` -------------------------------- ### Install .NET for Android Workload Source: https://github.com/dotnet/android/blob/main/README.md Installs the .NET for Android workload using the dotnet CLI. This workload provides the necessary bindings and tools for developing Android applications with .NET. ```bash dotnet workload install android ``` -------------------------------- ### Install Android Dependencies Source: https://github.com/dotnet/android/blob/main/Documentation/guides/InstallBuildsFromMain.md Installs necessary Android SDK components, specifically targeting API level 32. This command is used when the Android SDK platform for API level 32 is not found. It includes options to accept Android SDK licenses and specify manifest types. ```dotnetcli > dotnet build -t:InstallAndroidDependencies -p:AndroidManifestType=GoogleV2 -p:AcceptAndroidSDKLicenses=true ``` -------------------------------- ### Install Android Workload Source: https://github.com/dotnet/android/blob/main/Documentation/guides/InstallBuildsFromMain.md Installs the 'android' workload using dotnet CLI. It specifies NuGet sources for .NET 7 packages and the general NuGet repository. This command is essential for enabling Android development capabilities within the .NET MAUI project. ```dotnetcli > dotnet workload install android --source https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet7/nuget/v3/index.json --source https://api.nuget.org/v3/index.json ... Successfully installed workload(s) android. ``` -------------------------------- ### MSBuild Performance Summary Source: https://github.com/dotnet/android/blob/main/Documentation/guides/profiling.md Get a performance summary of your MSBuild project by running MSBuild with the /clp:performancesummary flag. This provides a breakdown of project evaluation, target, and task timings. ```bash msbuild YourProject.csproj /clp:performancesummary ``` -------------------------------- ### Full Unit Test Example Source: https://github.com/dotnet/android/blob/main/Documentation/workflow/UnitTests.md A complete unit test demonstrating how to set up MockBuildEngine, instantiate a task, execute it, and assert both task success and the absence of warnings. ```csharp [Test] public void MyTaskShouldSucceedWithNoWarnings { var warnings = new List (); var messages = new List (); var engine = new MockBuildEngine (TestContext.Out, warnings: warnings); var task = new MyTask () { BuildEngine = engine, }; Assert.IsTrue (task.Execute (), "Task should succeed."); Assert.AreEqual (0, warnings.Count, $"Task should not emit any warnings, found {warnings.Count}"); } ``` -------------------------------- ### Build and Start AOT Profiling Source: https://github.com/dotnet/android/blob/main/Documentation/guides/profiling.md Builds the Android application and starts the embedded AOT profiler on the device or emulator. This target is used to collect profiling data. ```bash msbuild /t:BuildAndStartAotProfiling ``` -------------------------------- ### Prepare .NET for Android Project Source: https://github.com/dotnet/android/blob/main/Documentation/building/windows/instructions.md Prepares the .NET for Android project by ensuring build dependencies are installed, updating git submodules, and downloading NuGet dependencies. This is a crucial first step before building. ```bash dotnet msbuild Xamarin.Android.sln -t:Prepare -nodeReuse:false dotnet msbuild external\Java.Interop\Java.Interop.sln -t:Prepare -nodeReuse:false ``` -------------------------------- ### SystemUpdatePolicy Install Window Properties Source: https://github.com/dotnet/android/blob/main/build-tools/enumification-helpers/remaining-int-methods-filtered.txt Defines the start and end times for the installation window of system updates. ```C# public virtual unsafe int InstallWindowEnd { get; set; } public virtual unsafe int InstallWindowStart { get; set; } ``` -------------------------------- ### jit-times Output Example Source: https://github.com/dotnet/android/blob/main/Documentation/guides/profiling.md The `jit-times` tool formats the JIT compilation data into a table showing total time, self time, and the method name, making it easier to identify performance bottlenecks. ```markdown | Total (ms) | Self (ms) | Method | | --: | --: | -- | | 20.08 | 20.08 | System.Reflection.Emit.OpCodes:.cctor () | | 23.29 | 19.61 | Java.Interop.JniRuntime:.ctor (Java.Interop.JniRuntime/CreationOptions) | | 9.34 | 8.59 | Android.Runtime.JNIEnv:Initialize (Android.Runtime.JnienvInitializeArgs*) | | 5.74 | 5.74 | string:SplitInternal (string,string[],int,System.StringSplitOptions) | | 5.17 | 5.17 | System.Text.StringBuilder:AppendFormatHelper (System.IFormatProvider,string,System.ParamsArray) | | 4.74 | 4.74 | Java.Interop.JniRuntime:InitJniBuiltinTypeNameMappings () | | 4.60 | 4.60 | Java.Interop.JniRuntime:InitJniBuiltinArrayMappings () | | 4.41 | 4.41 | Java.Interop.JniRuntime/JniTypeManager/d__11:MoveNext () | | 4.25 | 4.07 | System.MonoCustomAttrs:GetCustomAttributes (System.Reflection.ICustomAttributeProvider,System.Type,bool) | | 24.31 | 3.92 | Android.Runtime.JNINativeWrapper:CreateDelegate (System.Delegate) | | 19.64 | 3.79 | Java.Lang.Thread:get_DefaultUncaughtExceptionHandler () | ``` -------------------------------- ### Example Usage of D8/R8 Source: https://github.com/dotnet/android/blob/main/Documentation/guides/D8andR8.md Illustrates how D8 and R8 are invoked in the .NET for Android build process based on specific project configurations. ```bash # Example scenario where D8 would run: # $(AndroidEnableMultiDex) = False # $(AndroidLinkTool) = "proguard" (or any value other than "r8") # Example scenario where R8 would run: # $(AndroidEnableMultiDex) = True # $(AndroidLinkTool) = "r8" # Or: # $(AndroidEnableMultiDex) = False # $(AndroidLinkTool) = "r8" ``` -------------------------------- ### XA4310 Error Example Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/messages/xa4310.md This snippet shows an example of the XA4310 error message encountered in .NET for Android projects, highlighting the missing keystore file. ```text error XA4310: `$(Property)` file `filename.keystore` could not be found. ``` -------------------------------- ### Java.Text.IAttributedCharacterIterator Methods Source: https://github.com/dotnet/android/blob/main/build-tools/enumification-helpers/remaining-int-methods-filtered.txt Methods for getting run limits and starts based on attributes. ```C# public unsafe int GetRunLimit (Java.Text.AttributedCharacterIteratorAttribute attribute) public unsafe int GetRunLimit (System.Collections.Generic.ICollection attributes) public unsafe int GetRunStart (Java.Text.AttributedCharacterIteratorAttribute attribute) ``` -------------------------------- ### Release Notes Formatting Example (Build Performance) Source: https://github.com/dotnet/android/blob/main/Documentation/release-notes/README.md Demonstrates how to format release notes for build and deployment performance improvements, including linking to GitHub pull requests and providing a concise description of the change and its impact. ```markdown ### Build and deployment performance - [GitHub PR 3640](https://github.com/xamarin/xamarin-android/pull/3640): Use System.Reflection.Metadata rather than Cecil for `ResolveLibraryProjectImports`. This reduced the time for the `ResolveLibraryProjectImports` task from about 4.8 seconds to about 4.5 seconds for a small test Xamarin.Forms app on an initial clean build. ``` -------------------------------- ### Example Methods CSV Format Source: https://github.com/dotnet/android/blob/main/Documentation/workflow/HowToAddNewApiLevel.md This example shows the format of methods identified for potential enum mapping, where '?' indicates a decision is needed. ```csv ?,32,android/media,AudioAttributes,getSpatializationBehavior,return, ?,32,android/media,AudioAttributes$Builder,setSpatializationBehavior,sb, ``` -------------------------------- ### IAttributedCharacterIterator Methods Source: https://github.com/dotnet/android/blob/main/build-tools/enumification-helpers/remaining-int-methods-filtered.txt Provides methods for interacting with attributed character iterators, including getting run start and limit. ```C# public unsafe int GetRunStart (System.Collections.Generic.ICollection attributes) public unsafe int RunLimit { get; } public unsafe int RunStart { get; } ``` -------------------------------- ### Project Creation Templates Source: https://github.com/dotnet/android/wiki/Runtime-Performance-Ideas Demonstrates the command-line interface (CLI) commands used to create new Android and MAUI projects for performance testing. ```bash dotnet new android dotnet new maui ``` -------------------------------- ### XA4309 Example Message Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/messages/xa4309.md An example of the XA4309 warning message indicating that a specified MultiDexMainDexList file could not be found. ```text 'MultiDexMainDexList' file 'multidexcustom.keep' does not exist. ``` -------------------------------- ### Example Unit Test Source: https://github.com/dotnet/android/blob/main/Documentation/workflow/UnitTests.md A C# unit test example demonstrating how to assert properties of the `Application.Context` and a custom `App` class within the .NET for Android runtime. ```csharp [Test] public void ApplicationContextIsApp () { Assert.IsTrue (Application.Context is App); Assert.IsTrue (App.Created); } ``` -------------------------------- ### Listing Available Scenarios Source: https://github.com/dotnet/android/blob/main/build-tools/xaprepare/README.md This command lists all the available scenarios for the preparation utility. Scenarios are collections of steps to achieve a specific goal. ```makefile make PREPARE_ARGS=--ls ``` -------------------------------- ### aapt2 Tooling Issues Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/messages/index.md Diagnoses problems with the `aapt2` tool, including failure to get its version or `aapt2` not being installed. ```APIDOC XA0111: Could not get the `aapt2` version. Please check it is installed correctly. XA0112: `aapt2` is not installed. Disabling `aapt2` support. Please check it is installed correctly. ``` -------------------------------- ### Install .NET MAUI Source: https://github.com/dotnet/android/blob/main/Documentation/workflow/DevelopmentTips.md This MSBuild target installs .NET MAUI. Specify the desired version using the 'MauiVersion' property. This avoids conflicts with existing local Android workload builds. ```msbuild msbuild Xamarin.Android.sln -t:InstallMaui -p:MauiVersion=6.0.100-rc.1.1351 ``` -------------------------------- ### Clone xamarin-android Repository Source: https://github.com/dotnet/android/blob/main/Documentation/building/unix/instructions.md Clones the xamarin-android repository from GitHub. This is the first step in setting up the build environment. ```bash git clone https://github.com/xamarin/xamarin-android.git ``` -------------------------------- ### Install .NET for Android Dependencies using MSBuild Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/getting-started/installation/dependencies.md This command uses the `InstallAndroidDependencies` MSBuild target to automatically install required Android SDK components, platform tools, build tools, and emulator images. It allows specifying custom paths for the Android and Java SDKs and accepts necessary licenses. This is the recommended approach for ensuring all necessary dependencies are met for your .NET for Android project. ```dotnetcli dotnet build -t:InstallAndroidDependencies -f net8.0-android -p:AndroidSdkDirectory=c:\work\android-sdk -p:JavaSdkDirectory=c:\work\jdk -p:AcceptAndroidSdkLicenses=True ``` -------------------------------- ### Deploy APK Set Source: https://github.com/dotnet/android/blob/main/Documentation/guides/app-bundles.md Installs APKs extracted from an APK Set to a connected device. This command replaces any already installed package. It extracts and installs only the APKs that would be served to the specified device from the APK Set archive. If the app is not compatible or the archive is for a different device type, the command will fail. ```APIDOC bundletool install-apks --apks= [--adb=] [--allow-downgrade] [--device-id=] [--modules=] Description: Installs APKs extracted from an APK Set to a connected device. Replaces already installed package. This will extract from the APK Set archive and install only the APKs that would be served to that device. If the app is not compatible with the device or if the APK Set archive was generated for a different type of device, this command will fail. Parameters: --apks: Path to the archive file generated by the 'build-apks' command. Required. --adb: (Optional) Path to the adb utility. If absent, an attempt will be made to locate it if the ANDROID_HOME environment variable is set. --allow-downgrade: (Optional) If set, allows APKs to be installed on the device even if the app is already installed with a lower version code. --device-id: (Optional) Device serial name. If absent, this uses the ANDROID_SERIAL environment variable. Either this flag or the environment variable is required when more than one device or emulator is connected. --modules: (Optional) List of modules to be installed, or "_ALL_" for all modules. Defaults to modules installed during first install, i.e. not on-demand. Note that the dependent modules will also be installed. The value of this flag is ignored if the device receives a standalone APK. Example: bundletool install-apks --apks=foo.apks ``` -------------------------------- ### Android Telephony API - Emergency Number Management Source: https://github.com/dotnet/android/blob/main/tests/Xamarin.Android.Tools.Aidl-Tests/TestData/ITelephony.txt Provides methods for managing emergency number lists and their database versions. Includes functions to get the emergency number list in test mode, retrieve the version of the emergency number database, and notify when the OTA emergency number database is installed. ```APIDOC GetEmergencyNumberListTestMode() - Retrieves the list of emergency numbers in test mode. - Returns: A List of strings representing the emergency numbers. GetEmergencyNumberDbVersion(subId: int) - Retrieves the version of the emergency number database for a given subscription ID. - Parameters: - subId: The subscription ID. - Returns: An integer representing the database version. NotifyOtaEmergencyNumberDbInstalled() - Notifies the system that the OTA emergency number database has been installed. - No parameters or return value. ``` -------------------------------- ### MSBuild Best Practices Guide Source: https://github.com/dotnet/android/wiki/_Sidebar This guide outlines best practices for using MSBuild within the .NET for Android project. It focuses on improving build performance, maintainability, and reliability of the build system. ```markdown [MSBuild Best Practices](https://github.com/dotnet/android/blob/master/Documentation/guides/MSBuildBestPractices.md) ``` -------------------------------- ### Disable MSI-based Installers Source: https://github.com/dotnet/android/blob/main/Documentation/guides/WindowsOnArm64.md Removes a feature flag to disable MSI-based installers when .NET is installed to 'C:\Program Files\dotnet'. ```cmd C:\Program Files\dotnet\metadata\workloads\7.0.100\installertype\msi ``` -------------------------------- ### Build the Project (All Components) Source: https://github.com/dotnet/android/blob/main/Documentation/building/unix/instructions.md Builds all components of the project, including all TargetFrameworkVersions, ABIs, and Windows cross-compilers. Suitable for comprehensive builds. ```makefile make jenkins # -or- make jenkins MSBUILD=msbuild ``` -------------------------------- ### Rebuild Specific Mono Runtime and Install (Long Way) Source: https://github.com/dotnet/android/blob/main/Documentation/building/unix/instructions.md This process involves navigating to the specific architecture's build directory within `src/mono-runtimes/obj/$(Configuration)`, running 'make' to build the runtime for that ABI, and then using MSBuild to install the updated native libraries. ```bash # Example for armeabi-v7a $ make -C src/mono-runtimes/obj/Debug/armeabi-v7a # Install the updated native libraries $ msbuild /t:_InstallRuntimes src/mono-runtimes/mono-runtimes.csproj ``` -------------------------------- ### Interactive Program Notice (GPL) Source: https://github.com/dotnet/android/blob/main/build-tools/license-data/GPLv2.txt This example demonstrates the short notice that an interactive program should display upon startup when distributed under the GNU General Public License. It informs users about the program's warranty status and redistribution terms. ```text Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. ``` -------------------------------- ### Rebuild BCL Assemblies (Short Way) Source: https://github.com/dotnet/android/blob/main/Documentation/building/unix/instructions.md Allows rebuilding and installing a specific BCL assembly by providing its name via the ASSEMBLY Make variable, or rebuilding and installing all BCL assemblies. ```bash # Rebuild and install a specific BCL assembly rebuild-bcl-assembly ASSEMBLY=bcl_assembly_name # Rebuild and install all the BCL assemblies rebuild-all-bcl ``` -------------------------------- ### Dotnet CLI Project Templates Source: https://github.com/dotnet/android/blob/main/Documentation/guides/OneDotNet.md Demonstrates how to use the dotnet CLI to create new Android projects and items. It lists available templates and provides examples for creating applications, libraries, and activities. ```bash dotnet new android --output MyAndroidApp --packageName com.mycompany.myandroidapp dotnet new androidlib --output MyAndroidLibrary dotnet new android-bindinglib --output MyJavaBinding ``` ```bash dotnet new android-activity --name LoginActivity --namespace MyAndroidApp dotnet new android-layout --name MyLayout --output Resources/layout ``` -------------------------------- ### Running the Preparation Utility Source: https://github.com/dotnet/android/blob/main/build-tools/xaprepare/README.md This command executes the main preparation utility from the root of the .NET for Android source tree. It uses the default 'Standard' scenario if none is specified. ```makefile make prepare ``` -------------------------------- ### XA0136: Corrupted Package Installation Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/messages/index.md The current installation of the package is corrupted. Manually uninstall the package from all user profiles on the device and attempt installation again. If the issue persists, consider disabling Fast Deployment. ```text XA0136: The currently installation of the package in corrupt. Please manually uninstall the package from all the users on device and try again. If that does not work you can disable Fast Deployment. ``` -------------------------------- ### APT0001 Error Example Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/messages/apt0001.md An example of the APT0001 error message encountered in .NET for Android projects, indicating an unknown option passed to the aapt2 tool. ```bash error APT0001: Unknown option `--ignore-assets`. Please check `$(AndroidAapt2CompileExtraArgs)` and `$(AndroidAapt2LinkExtraArgs)` to see if they include any `aapt` command line arguments that are no longer valid for `aapt2` and ensure that all other arguments are valid for `aapt2`. ``` -------------------------------- ### Interpreting simpleperf Report (Default Sort) Source: https://github.com/dotnet/android/blob/main/Documentation/guides/profiling.md Example output from `simpleperf report` showing profiling results sorted by overhead and command. It details the command line used, architecture, event type, samples, event count, and a breakdown of overhead by shared object and symbol. ```bash > python report.py Cmdline: /data/data/Xamarin.Forms_Performance_Integration/simpleperf record --in-app --tracepoint-events /data/local/tmp/tracepoint_events -o perf.data -e task-clock:u -f 1000 -g --duration 10 --symfs /data/local/tmp/native_libs/ --app Xamarin.Forms_Performance_Integration Arch: x86 Event: task-clock:u (type 1, config 1) Samples: 1558 Event count: 1558000000 Overhead Command Pid Tid Shared Object Symbol 97.88% Xamarin.Forms_Performance_Integration 6527 6527 [vdso] __vdso_clock_gettime 0.13% RenderThread 6527 6548 [vdso] __vdso_clock_gettime 0.13% Xamarin.Forms_Performance_Integration 6527 6527 /system/lib/libdexfile.so art::IsValidPartOfMemberNameUtf8(char const**) 0.06% Binder:6527_3 6527 6542 [vdso] __vdso_clock_gettime 0.06% Jit thread pool 6527 6533 [vdso] __vdso_clock_gettime 0.06% Xamarin.Forms_Performance_Integration 6527 6527 /data/app/Mono.Android.DebugRuntime-wbwmv22rlkqD4wNWY5gjpQ==/lib/x86/libmonosgen-32bit-2.0.so libmonosgen-32bit-2.0.so[+21bf4c] 0.06% Xamarin.Forms_Performance_Integration 6527 6527 /data/app/Mono.Android.DebugRuntime-wbwmv22rlkqD4wNWY5gjpQ==/lib/x86/libmonosgen-32bit-2.0.so libmonosgen-32bit-2.0.so[+23ddf9] ... ``` -------------------------------- ### XA0132: Package Installation Failure Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/messages/index.md The package could not be installed, likely due to a pre-existing installation under a different user profile. Uninstall the package manually via the device's Settings app and try again. ```text XA0132: The package was not installed. Please check you do not have it installed under any other user. If the package does show up on the device, try manually uninstalling it then try again. You should be able to uninstall the app via the Settings app on the device. ``` -------------------------------- ### Android SocketKeepalive Start Source: https://github.com/dotnet/android/blob/main/build-tools/enumification-helpers/remaining-int-methods-filtered.txt Starts socket keepalive with a specified interval in seconds. ```C# public unsafe void Start (int intervalSec) ``` -------------------------------- ### Example Constants CSV Format Source: https://github.com/dotnet/android/blob/main/Documentation/workflow/HowToAddNewApiLevel.md This example shows the format of constants extracted from an API level, where '?' indicates that a determination needs to be made regarding enumification. ```csv ?,32,android/media/Spatializer.SPATIALIZER_IMMERSIVE_LEVEL_MULTICHANNEL,1,,,, ?,32,android/media/Spatializer.SPATIALIZER_IMMERSIVE_LEVEL_NONE,0,,,, ?,32,android/media/Spatializer.SPATIALIZER_IMMERSIVE_LEVEL_OTHER,-1,,,, ``` -------------------------------- ### Android Content PM Package Installer Constants Source: https://github.com/dotnet/android/blob/main/build-tools/enumification-helpers/remaining-int-consts.txt Defines a constant for an invalid identifier in the package installer. ```csharp public const int InvalidId = (int) -1; ``` -------------------------------- ### Install Android Workload Source: https://github.com/dotnet/android/blob/main/Documentation/guides/WindowsOnArm64.md Installs the Android workload for .NET. It's crucial to use '--skip-manifest-update' to preserve manual changes and specify the NuGet sources. ```dotnetcli > dotnet workload install android --skip-manifest-update --source https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet7/nuget/v3/index.json --source https://api.nuget.org/v3/index.json ``` -------------------------------- ### Android Application Start Component Constants Source: https://github.com/dotnet/android/blob/main/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt Constants defining different types of application start components. ```csharp const Android.App.ApplicationStartInfo.StartComponentActivity = Android.App.ApplicationStartInfoStartComponent.Activity -> Android.App.ApplicationStartInfoStartComponent const Android.App.ApplicationStartInfo.StartComponentBroadcast = Android.App.ApplicationStartInfoStartComponent.Broadcast -> Android.App.ApplicationStartInfoStartComponent const Android.App.ApplicationStartInfo.StartComponentContentProvider = Android.App.ApplicationStartInfoStartComponent.ContentProvider -> Android.App.ApplicationStartInfoStartComponent const Android.App.ApplicationStartInfo.StartComponentOther = Android.App.ApplicationStartInfoStartComponent.Other -> Android.App.ApplicationStartInfoStartComponent const Android.App.ApplicationStartInfo.StartComponentService = Android.App.ApplicationStartInfoStartComponent.Service -> Android.App.ApplicationStartInfoStartComponent ``` -------------------------------- ### dotnet-trace Output Example Source: https://github.com/dotnet/android/blob/main/Documentation/guides/tracing.md Example output from `dotnet-trace` when attached to a running .NET for Android application. It shows the recording progress and indicates when the trace is complete and output files are being written. ```sh Process : $HOME/.dotnet/tools/dotnet-dsrouter Output File : /tmp/hellomaui-app-trace [00:00:00:35] Recording trace 1.7997 (MB) Press or to exit...812 (KB) ``` -------------------------------- ### Interpreting methods.txt Source: https://github.com/dotnet/android/blob/main/Documentation/guides/profiling.md The `methods.txt` file contains individual JIT compilation times for each method. This raw data can be difficult to read, but it can be processed by the `jit-times` command-line tool for a more readable and sorted output. ```text JIT method begin: System.OutOfMemoryException:.ctor (string) elapsed: 0s:20::136721 JIT method done: System.OutOfMemoryException:.ctor (string) elapsed: 0s:20::605627 ``` -------------------------------- ### Named Link Styles Source: https://github.com/dotnet/android/blob/main/Documentation/release-notes/README.md Examples of named link styles used for updating release information on aka.ms. ```shell xamarin-android-commercial-preview-windows ``` ```shell xamarin-android-commercial-d16-9-windows ``` -------------------------------- ### Android AdServices Rendering and Training Examples API Source: https://github.com/dotnet/android/blob/main/src/Mono.Android/PublicAPI/API-36/PublicAPI.Unshipped.txt Provides constructors for rendering inputs and training examples. The rendering input allows specifying dimensions and configuration, while training examples input requires population and task names, with optional resumption tokens and collection names. ```APIDOC Android.AdServices.OnDevicePersonalization.RenderInput.RenderInput(int width, int height, Android.AdServices.OnDevicePersonalization.RenderingConfig? renderingConfig) -> void Android.AdServices.OnDevicePersonalization.TrainingExamplesInput.CollectionName.get -> string? Android.AdServices.OnDevicePersonalization.TrainingExamplesInput.TrainingExamplesInput(string! populationName, string! taskName, byte[]? resumptionToken, string? collectionName) -> void ``` -------------------------------- ### Build .NET for Android Project Source: https://github.com/dotnet/android/blob/main/Documentation/building/windows/instructions.md Builds the .NET for Android solution. This command compiles the main project after preparation steps are completed. ```bash dotnet-local.cmd build Xamarin.Android.sln -nodeReuse:false ``` -------------------------------- ### Prepend Word Bound Replacement Example Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/binding-libs/customizing-bindings/namespace-customization.md This example shows how to constrain a replacement to the beginning of a namespace part by prepending a '.'. This ensures that 'Androidx.Core' is matched, but not 'Square.OkHttp.Androidx'. ```xml ``` -------------------------------- ### Example Messages for XA1027 and XA1011 Source: https://github.com/dotnet/android/blob/main/Documentation/docs-mobile/messages/xa1027.md Displays example error messages related to Android build warnings XA1027 and XA1011, highlighting issues with ProGuard and D8 compatibility. ```csharp warning XA1027: The 'EnableProguard' MSBuild property is set to 'true' and the 'AndroidLinkTool' MSBuild property is empty, so 'AndroidLinkTool' will default to 'proguard'. error XA1011: Using ProGuard with the D8 DEX compiler is no longer supported. Please set the code shrinker to 'r8' in the Visual Studio project property pages or edit the project file in a text editor and set the 'AndroidLinkTool' MSBuild property to 'r8'. ``` -------------------------------- ### Provision .NET SDK and Android Workload Source: https://github.com/dotnet/android/blob/main/Documentation/workflow/DevelopmentTips.md This command provisions a .NET SDK and a locally built Android workload. The output is placed in the 'bin/$(Configuration)/dotnet/' directory. ```msbuild make pack-dotnet or msbuild Xamarin.Android.sln -t:PackDotNet ``` -------------------------------- ### Pushing gdbserver and setting permissions Source: https://github.com/dotnet/android/blob/main/Documentation/workflow/DevelopmentTips.md This snippet demonstrates how to push the gdbserver executable to the Android device, set execute permissions for the application's data directory, and then execute gdbserver to attach to a running process. ```bash $ adb push ~/Library/Developer/Xamarin/android-sdk-macosx/ndk-bundle/prebuilt/android-arm64/gdbserver/gdbserver \ /data/local/tmp/ && \ adb shell run-as Mono.Android_Tests cp /data/local/tmp/gdbserver ./ && \ adb shell run-as Mono.Android_Tests chmod +x ./gdbserver $ adb shell run-as Mono.Android_Tests \ chmod a+x /data/data/Mono.Android_Tests/ ```