A .NET 8, NativeAOT example on Android
A .NET 8, NativeAOT example on Android.
Configure your environment: the following environment variables are required:
ANDROID_NDK_HOME: The path to an Android NDK installation.ANDROID_HOME: The path to an Android SDK installation.Build the project:
dotnet build
dotnet publish DotNet/libdotnet.csproj
(cd Native && ./gradlew assembleRelease)Install the app:
$ANDROID_HOME/platform-tools/adb install Native/app/build/outputs/apk/release/app-release.apkRun the app:
$ANDROID_HOME/platform-tools/adb shell am start com.jonathanpeppers.nativeaot/android.app.NativeActivityThis sample has a C++ Android Studio project:
Some screenshots of the Skia content:
(Note these look completely smooth on a Pixel 5, I just tried to snap quick gifs with Vysor)
The C# side is a:
linux-bionic-arm64The release .apk file of the SkiaSharp sample is ~4.26 MB
A breakdown of the files inside:
…libdotnet.so is ~1.07 MB, and libSkiaSharp.so is ~8.5MB!
If we reduce this to a "Hello World" example:
hello.apk is ~430 KB!libdotnet.so (uncompressed) is ~821 KB!The average of 10 runs on a Pixel 5 of the SkiaSharp sample:
Average(ms): 121
Std Err(ms): 3.29983164553722
Std Dev(ms): 10.434983894999Average of 10 runs on a Pixel 5 of the "Hello World" example:
Average(ms): 120.9
Std Err(ms): 2.97937353594118
Std Dev(ms): 9.42160637400367They might be effectively the same.
For comparison (as of .NET 8), a dotnet new android app is about ~180ms on a
Pixel 5, and dotnet new maui is about ~560ms.
Source: https://github.com/jonathanpeppers/maui-profiling
See the HelloWorld branch.
I had this managed code:
[UnmanagedCallersOnly(EntryPoint = "ManagedAdd")]
public static int ManagedAdd(int x, int y) => x + y;I created a C++ Android project using NativeActivity, and I called the managed code from C++:
// in dotnet.h
extern "C" int ManagedAdd(int x, int y);
// in native-lib.cpp
int result = ManagedAdd(1, 2);
__android_log_print (ANDROID_LOG_INFO, TAG, "ManagedAdd(1, 2) returned: %i", result);Results in the message:
01-31 11:42:44.545 28239 28259 I NATIVE : Entering android_main
01-31 11:42:44.550 28239 28259 I NATIVE : ManagedAdd(1, 2) returned: 3See DotNet/README.md on how to build libdotnet.so.
Console.WriteLine() doesn't work because it basically just writes to Unix stdout. stdout does not appear in adb logcat output, as you have to call __android_log_print instead.
This was an interesting example, to start a thread that processes stdout and calls the appropriate Android API:
Instead, we can p/invoke into:
[DllImport("log", EntryPoint = "__android_log_print", CallingConvention = CallingConvention.Cdecl)]
public static extern int LogPrint(LogPriority priority, string tag, string format);No open issues yet, or sync has not completed.