Updated example to not use native activity anymore

This commit is contained in:
Alejandro Saucedo 2020-10-03 18:27:39 +01:00
parent ba70a4c666
commit a73f82e191
23 changed files with 321 additions and 163 deletions

View file

@ -1,4 +1,6 @@
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
@ -6,12 +8,13 @@ def ndkDir = properties.getProperty('ndk.dir')
def valLayerBinDir = "${ndkDir}/sources/third_party/vulkan/src/build-android/jniLibs"
android {
compileSdkVersion 26
compileSdkVersion 29
ndkVersion '21.2.6472646'
defaultConfig {
applicationId "com.ethicalml.kompute.examples.android"
minSdkVersion 26
targetSdkVersion 26
targetSdkVersion 29
versionCode = 1
versionName = "0.0.1"
externalNativeBuild {
@ -26,29 +29,57 @@ android {
}
}
}
buildFeatures {
viewBinding true
}
buildTypes {
release {
minifyEnabled = false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path 'src/main/jni/CMakeLists.txt'
path 'src/main/cpp/CMakeLists.txt'
}
}
sourceSets {
main {
jniLibs {
// Must have ndk-r12 or better which including layer binaries
srcDirs = ["${valLayerBinDir}"]
// Must have ndk-r12 or better which including layer binaries
srcDirs = ["${valLayerBinDir}"]
}
}
}
buildTypes {
release {
minifyEnabled = false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
flavorDimensions 'cpuArch'
productFlavors {
arm8 {
dimension 'cpuArch'
ndk {
abiFilters 'arm64-v8a', 'armeabi-v7a'
}
}
}
x86_64 {
dimension 'cpuArch'
ndk {
abiFilters 'x86_64', 'x86'
}
}
universal {
dimension 'cpuArch'
// include all default ABIs. with NDK-r16, it is:
// armeabi-v7a, arm64-v8a, x86, x86_64
}
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation fileTree(dir: 'libs', include: ['*.jar'])
}

View file

@ -5,23 +5,35 @@
android:versionCode="1"
android:versionName="1.0">
<application android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<!-- Our activity is the built-in NativeActivity framework class.
This will take care of integrating with our NDK code. -->
<activity android:name="android.app.NativeActivity"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<!-- Tell NativeActivity the name of or .so -->
<meta-data android:name="android.app.lib_name"
android:value="kompute_android" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- <application android:label="@string/app_name"-->
<!-- android:theme="@android:style/Theme.NoTitleBar.Fullscreen">-->
<!-- &lt;!&ndash; Our activity is the built-in NativeActivity framework class.-->
<!-- This will take care of integrating with our NDK code. &ndash;&gt;-->
<!-- <activity android:name="android.app.NativeActivity"-->
<!-- android:label="@string/app_name"-->
<!-- android:configChanges="orientation|keyboardHidden">-->
<!-- &lt;!&ndash; Tell NativeActivity the name of or .so &ndash;&gt;-->
<!-- <meta-data android:name="android.app.lib_name"-->
<!-- android:value="kompute_android" />-->
<!-- <intent-filter>-->
<!-- <action android:name="android.intent.action.MAIN" />-->
<!-- <category android:name="android.intent.category.LAUNCHER" />-->
<!-- </intent-filter>-->
<!-- </activity>-->
<!-- </application>-->
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".KomputeJni">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<!-- END_INCLUDE(manifest) -->

View file

@ -6,14 +6,14 @@ set(ANDROID_APP_GLUE_DIR ${ANDROID_NDK}/sources/android/native_app_glue)
set(VK_ANDROID_COMMON_DIR ${ANDROID_NDK}/sources/third_party/vulkan/src/common)
set(VK_ANDROID_INCLUDE_DIR ${ANDROID_NDK}/sources/third_party/vulkan/src/include)
# build native_app_glue as a static lib
include_directories(${ANDROID_APP_GLUE_DIR})
add_library(app-glue STATIC
${ANDROID_APP_GLUE_DIR}/android_native_app_glue.c)
## build native_app_glue as a static lib
#include_directories(${ANDROID_APP_GLUE_DIR})
#add_library(app-glue STATIC
# ${ANDROID_APP_GLUE_DIR}/android_native_app_glue.c)
# build vulkan app
add_library(kompute_android SHARED
main.cpp)
KomputeJniNative.cpp)
include_directories(
${VK_ANDROID_COMMON_DIR}
@ -29,7 +29,7 @@ set(CMAKE_SHARED_LINKER_FLAGS
target_link_libraries(kompute_android
kompute
app-glue
# app-glue
log
kompute_vk_ndk_wrapper
android)

View file

@ -0,0 +1,111 @@
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//#undef DEBUG
//#define RELEASE 1
#include <android/log.h>
//#include <android_native_app_glue.h>
//#include <cassert>
//#include <memory>
//#include <vector>
//#include <unistd.h>
#include <string.h>
#include <jni.h>
//#include "kompute/Kompute.hpp"
// Functions interacting with Android native activity
void android_main(struct android_app* state);
void terminate(void);
void handle_cmd(android_app* app, int32_t cmd);
// Android log function wrappers
static const char* kTAG = "Vulkan-Tutorial01";
#define LOGI(...) \
((void)__android_log_print(ANDROID_LOG_INFO, kTAG, __VA_ARGS__))
#define LOGW(...) \
((void)__android_log_print(ANDROID_LOG_WARN, kTAG, __VA_ARGS__))
#define LOGE(...) \
((void)__android_log_print(ANDROID_LOG_ERROR, kTAG, __VA_ARGS__))
JNIEXPORT jstring JNICALL
Java_com_ethicalml_kompute_examples_android_KomputeJni_stringFromJNI(JNIEnv *env, jobject thiz) {
#if defined(__arm__)
#if defined(__ARM_ARCH_7A__)
#if defined(__ARM_NEON__)
#if defined(__ARM_PCS_VFP)
#define ABI "armeabi-v7a/NEON (hard-float)"
#else
#define ABI "armeabi-v7a/NEON"
#endif
#else
#if defined(__ARM_PCS_VFP)
#define ABI "armeabi-v7a (hard-float)"
#else
#define ABI "armeabi-v7a"
#endif
#endif
#else
#define ABI "armeabi"
#endif
#elif defined(__i386__)
#define ABI "x86"
#elif defined(__x86_64__)
#define ABI "x86_64"
#elif defined(__mips64) /* mips64el-* toolchain defines __mips__ too */
#define ABI "mips64"
#elif defined(__mips__)
#define ABI "mips"
#elif defined(__aarch64__)
#define ABI "arm64-v8a"
#else
#define ABI "unknown"
#endif
LOGI("Initialising vulkan");
// if (!InitVulkan()) {
// LOGE("Vulkan is unavailable, install vulkan and re-start");
// return false;
// }
//
// LOGI("Creating manager");
//
// kp::Manager mgr;
//
// auto tensorA = mgr.buildTensor({0,1,2});
// auto tensorB = mgr.buildTensor({0,1,2});
// auto tensorC = mgr.buildTensor({1,2,3});
//
// LOGI("Result before:");
// for(const float & i : tensorC->data()) {
// LOGI("%f ", i);
// }
//
// mgr.evalOpDefault<kp::OpMult<>>({tensorA, tensorB, tensorC});
// mgr.evalOpDefault<kp::OpTensorSyncLocal>({tensorC});
//
// LOGI("Result after:");
// for(const float & i : tensorC->data()) {
// LOGI("%f ", i);
// }
return (*env).NewStringUTF("Hello from JNI ! Compiled with ABI ");
}

View file

@ -0,0 +1,68 @@
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ethicalml.kompute.examples.android
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.ethicalml.kompute.examples.android.databinding.ActivityHelloJniBinding
class KomputeJni : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
/*
* Retrieve our TextView and set its content.
* the text is retrieved by calling a native
* function.
*/
val binding = ActivityHelloJniBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.helloTextview.text = stringFromJNI()
}
/*
* A native method that is implemented by the
* 'hello-jni' native library, which is packaged
* with this application.
*/
external fun stringFromJNI(): String?
/*
* This is another native method declaration that is *not*
* implemented by 'hello-jni'. This is simply to show that
* you can declare as many native methods in your Java code
* as you want, their implementation is searched in the
* currently loaded native libraries only the first time
* you call them.
*
* Trying to call this function will result in a
* java.lang.UnsatisfiedLinkError exception !
*/
external fun unimplementedStringFromJNI(): String?
companion object {
/*
* this is used to load the 'hello-jni' library on application
* startup. The library has already been unpacked into
* /data/data/com.example.hellojni/lib/libhello-jni.so
* at the installation time by the package manager.
*/
init {
System.loadLibrary("kompute_android")
}
}
}

View file

@ -1,114 +0,0 @@
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#undef DEBUG
#define RELEASE 1
#include <android/log.h>
#include <android_native_app_glue.h>
#include <cassert>
#include <memory>
#include <vector>
#include <unistd.h>
#include "kompute/Kompute.hpp"
// Android log function wrappers
static const char* kTAG = "Vulkan-Tutorial01";
#define LOGI(...) \
((void)__android_log_print(ANDROID_LOG_INFO, kTAG, __VA_ARGS__))
#define LOGW(...) \
((void)__android_log_print(ANDROID_LOG_WARN, kTAG, __VA_ARGS__))
#define LOGE(...) \
((void)__android_log_print(ANDROID_LOG_ERROR, kTAG, __VA_ARGS__))
// We will call this function the window is opened.
// This is where we will initialise everything
bool initialized_ = false;
bool initialize(android_app* app);
// Functions interacting with Android native activity
void android_main(struct android_app* state);
void terminate(void);
void handle_cmd(android_app* app, int32_t cmd);
// typical Android NativeActivity entry function
void android_main(struct android_app* app) {
app->onAppCmd = handle_cmd;
int events;
android_poll_source* source;
do {
if (ALooper_pollAll(initialized_ ? 1 : 0, nullptr, &events,
(void**)&source) >= 0) {
if (source != NULL) source->process(app, source);
}
} while (app->destroyRequested == 0);
}
bool initialize(android_app* app) {
LOGI("Initialising vulkan");
if (!InitVulkan()) {
LOGE("Vulkan is unavailable, install vulkan and re-start");
return false;
}
LOGI("Creating manager");
kp::Manager mgr;
auto tensorA = mgr.buildTensor({0,1,2});
auto tensorB = mgr.buildTensor({0,1,2});
auto tensorC = mgr.buildTensor({1,2,3});
LOGI("Result before:");
for(const float & i : tensorC->data()) {
LOGI("%f ", i);
}
mgr.evalOpDefault<kp::OpMult<>>({tensorA, tensorB, tensorC});
mgr.evalOpDefault<kp::OpTensorSyncLocal>({tensorC});
LOGI("Result after:");
for(const float & i : tensorC->data()) {
LOGI("%f ", i);
}
initialized_ = true;
return 0;
}
void terminate(void) {
initialized_ = false;
}
// Process the next main command.
void handle_cmd(android_app* app, int32_t cmd) {
switch (cmd) {
case APP_CMD_INIT_WINDOW:
// The window is being shown, get it ready.
initialize(app);
break;
case APP_CMD_TERM_WINDOW:
// The window is being hidden or closed, clean it up.
terminate();
break;
default:
LOGI("event not handled: %d", cmd);
}
}

View file

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_hello_jni"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hellojni.HelloJni">
<TextView
android:id="@+id/hello_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="@+id/activity_hello_jni"
app:layout_constraintLeft_toLeftOf="@+id/activity_hello_jni"
app:layout_constraintRight_toRightOf="@+id/activity_hello_jni"
app:layout_constraintTop_toTopOf="@+id/activity_hello_jni" />
</androidx.constraintlayout.widget.ConstraintLayout>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

View file

@ -0,0 +1,6 @@
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>

View file

@ -0,0 +1,5 @@
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>

View file

@ -1,4 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Kompute Android Example</string>
<string name="app_name">KomputeJni</string>
</resources>

View file

@ -0,0 +1,11 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>

View file

@ -1,14 +1,15 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.3.72'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'com.android.tools.build:gradle:4.0.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

View file

@ -11,8 +11,10 @@
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# org.gradle.parallel=true
android.useAndroidX=true

View file

@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip