diff --git a/source-android/androidnative.pri/LICENSE b/source-android/androidnative.pri/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/source-android/androidnative.pri/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. diff --git a/source-android/androidnative.pri/README.md b/source-android/androidnative.pri/README.md new file mode 100644 index 0000000..5678fd4 --- /dev/null +++ b/source-android/androidnative.pri/README.md @@ -0,0 +1,141 @@ +Calling Android functions from Qt without using JNI +=========================== + +It is a fork of the [Quick Android](https://github.com/benlau/quickandroid) project that aims to provide a library to access Android functions from Qt/QML without using JNI. + +Remarks: This project only support gradle build system. + +Features +======== + + 1. SystemDispatcher - A message queue for C++/Qt and Java/Android + 1. Send message in C++, receive in Java and vice versa. + 1. Data type will be converted automatically (e.g QMap <-> java.util.Map). No need to write in JNI. + 1. It could be used to write your own Java code + 1. Bundled Components + 1. Image Picker + 1. Toast + 1. Wrapper of android.os.Environment / android.os.Debug / MediaScannerConnection + +C++ API +======= + + 1. Environment::getExternalStoragePublicDirectory() + 1. MediaScannerConnection::scanFile() + 1. Debug::getNativeHeapSize() + 1. Debug::getNativeHeapAllocatedSize() + +The functions above do not require to config gradle before using. + +QML Components +============== + +``` + import AndroidNative 1.0 +``` + + 1. ImagePicker + 1. Toast + + +SystemDispatcher +================ + +SystemDispatcher is a message queue component for delivering action message between C++/QML and Java. Data type in message is converted to the target platform automatically (e.g QMap <-> java.util.Map) . So that user doesn't need to write JNI to access their Java functions. + +Moreover, SystemDispatcher is compilable on a non-Android platform. It doesn't cause any trouble to run on your development host. + +``` +// C++ Example + +#include + +// Load a Java class. It will trigger the code within `static` block +SystemDispatcher::instance()->loadClass("androidnative.example.ExampleService"); + +QVariantMap message; +message["value1"] = 1; +message["value2"] = 2.0; +message["value3"] = "3"; + +// Dispatch a message +SystemDispatcher::instance()->dispatch("androidnative.example.dummyAction", message); + +``` + +``` +// QML Example + +import AndroidNative 1.0 + +Item { + + Component.onCompleted: { + var message = { + value1: 1, + value2: 2.0, + value3: "3" + } + SystemDispatcher.dispatch("androidnative.example.dummyAction", message); + } +} +``` + +``` +// Java Receiver + +public class ExampleService { + + static { + + SystemDispatcher.addListener(new SystemDispatcher.Listener() { + + public void onDispatched(String type , Map message) { + + if (type.equals("androidnative.example.dummyAction")) { + // Process then dispatch a response back to C++/QML + SystemDispatcher.dispatch(("androidnative.example.response"); + + return; + } + return; + } + }); + } +} + +``` + +``` +// Listen from QML + +Connections { + target: SystemDispatcher + onDispatched: { + // process the message + } +} +``` + + +Supported data type: + +| Qt | Java | +|--------------|---------| +| int | int | +| bool | boolean | +| QString | String | +| QVariantList | List | +| QVariantMap | Map | + +Installation Instruction +======================== + +[androidnative.pri/installation.md at master · benlau/androidnative.pri](https://github.com/benlau/androidnative.pri/blob/master/docs/installation.md) + +Example +======= + +An example program is available at: [androidnative.pri/examples/androidnativeexample at master · benlau/androidnative.pri](https://github.com/benlau/androidnative.pri/tree/master/examples/androidnativeexample) + +![example1.png (533×472)](https://raw.githubusercontent.com/benlau/androidnative.pri/master/docs/screenshots/example1.png) diff --git a/source-android/androidnative.pri/androidnative.pri b/source-android/androidnative.pri/androidnative.pri new file mode 100644 index 0000000..0f443ba --- /dev/null +++ b/source-android/androidnative.pri/androidnative.pri @@ -0,0 +1,25 @@ +android { + QT += androidextras +} + +QML_IMPORT_PATH += $$PWD + +INCLUDEPATH += $$PWD/cpp +RESOURCES += \ + $$PWD/qml/androidnative.qrc + +HEADERS += \ + $$PWD/cpp/AndroidNative/priv/systemdispatcherproxy.h \ + $$PWD/cpp/AndroidNative/systemdispatcher.h \ + $$PWD/cpp/AndroidNative/environment.h \ + $$PWD/cpp/AndroidNative/debug.h \ + $$PWD/cpp/AndroidNative/mediascannerconnection.h + +SOURCES += \ + $$PWD/cpp/AndroidNative/priv/systemdispatcherproxy.cpp \ + $$PWD/cpp/AndroidNative/systemdispatcher.cpp \ + $$PWD/cpp/AndroidNative/environment.cpp \ + $$PWD/cpp/AndroidNative/debug.cpp \ + $$PWD/cpp/AndroidNative/mediascannerconnection.cpp \ + $$PWD/cpp/AndroidNative/priv/androidnativeqmltypes.cpp + diff --git a/source-android/androidnative.pri/ci/qt-android b/source-android/androidnative.pri/ci/qt-android new file mode 100755 index 0000000..d16dac4 --- /dev/null +++ b/source-android/androidnative.pri/ci/qt-android @@ -0,0 +1,16 @@ +#!/bin/sh + +echo Downloading Qt +wget -c --no-check-certificate -nv https://download.qt.io/archive/qt/5.7/5.7.0/qt-opensource-linux-x64-android-5.7.0.run +echo Installing Qt +extract-qt-installer qt-opensource-linux-x64-android-5.7.0.run $PWD/Qt +install-android-sdk platform-tool,build-tools-22.0.1,android-19,android-21 + +echo Create qt.env +cat << EOF > qt.env +export QT_ROOT=$PWD/Qt +export QT_HOME=$PWD/Qt/5.7 +export PATH=$PWD/Qt/5.7/android_armv7/bin:$PWD/android-sdk-linux/tools:$PATH +export ANDROID_NDK_ROOT=$PWD/android-ndk-r10c +export ANDROID_SDK_ROOT=$PWD/android-sdk-linux +EOF diff --git a/source-android/androidnative.pri/cpp/AndroidNative/debug.cpp b/source-android/androidnative.pri/cpp/AndroidNative/debug.cpp new file mode 100644 index 0000000..77f4d37 --- /dev/null +++ b/source-android/androidnative.pri/cpp/AndroidNative/debug.cpp @@ -0,0 +1,47 @@ +#include +#include "debug.h" +#ifdef Q_OS_ANDROID +#include +#include +#endif + +long AndroidNative::Debug::getNativeHeapSize() +{ +#ifdef Q_OS_ANDROID + QAndroidJniEnvironment env; + + jclass clazz = env->FindClass("android/os/Debug"); + if (clazz) + { + jmethodID mid = env->GetStaticMethodID(clazz, "getNativeHeapSize", "()J"); + if (mid) + { + return env->CallStaticLongMethod(clazz, mid); + } + } + return -1L; +#else + return -1L; +#endif +} + + +long AndroidNative::Debug::getNativeHeapAllocatedSize() +{ +#ifdef Q_OS_ANDROID + QAndroidJniEnvironment env; + + jclass clazz = env->FindClass("android/os/Debug"); + if (clazz) + { + jmethodID mid = env->GetStaticMethodID(clazz, "getNativeHeapAllocatedSize", "()J"); + if (mid) + { + return env->CallStaticLongMethod(clazz, mid); + } + } + return -1L; +#else + return -1L; +#endif +} diff --git a/source-android/androidnative.pri/cpp/AndroidNative/debug.h b/source-android/androidnative.pri/cpp/AndroidNative/debug.h new file mode 100644 index 0000000..a084b0c --- /dev/null +++ b/source-android/androidnative.pri/cpp/AndroidNative/debug.h @@ -0,0 +1,18 @@ +#ifndef DEBUG_H +#define DEBUG_H + +namespace AndroidNative { + + namespace Debug { + + long getNativeHeapSize(); + + long getNativeHeapAllocatedSize(); + + + } + +} + + +#endif // DEBUG_H diff --git a/source-android/androidnative.pri/cpp/AndroidNative/environment.cpp b/source-android/androidnative.pri/cpp/AndroidNative/environment.cpp new file mode 100644 index 0000000..e50d525 --- /dev/null +++ b/source-android/androidnative.pri/cpp/AndroidNative/environment.cpp @@ -0,0 +1,33 @@ +#include +#include +#include "environment.h" +#ifdef Q_OS_ANDROID +#include +#include +#endif + +QString AndroidNative::Environment::DIRECTORY_DCIM = "DIRECTORY_DCIM"; + +QString AndroidNative::Environment::getExternalStoragePublicDirectory(const QString &type) +{ + QString res; + +#ifdef Q_OS_ANDROID + QAndroidJniObject jniType = QAndroidJniObject::getStaticObjectField("android/os/Environment", type.toUtf8().constData()); + + QAndroidJniObject file = QAndroidJniObject::callStaticObjectMethod("android/os/Environment", + "getExternalStoragePublicDirectory", + "(Ljava/lang/String;)Ljava/io/File;", + jniType.object()); + QAndroidJniObject absolutePath = file.callObjectMethod("getAbsolutePath","()Ljava/lang/String;"); + res = absolutePath.toString(); + +#else + if (type == DIRECTORY_DCIM) { + res = QStandardPaths::standardLocations(QStandardPaths::PicturesLocation)[0]; + } else { + res = QDir::currentPath(); + } +#endif + return res; +} diff --git a/source-android/androidnative.pri/cpp/AndroidNative/environment.h b/source-android/androidnative.pri/cpp/AndroidNative/environment.h new file mode 100644 index 0000000..95005b6 --- /dev/null +++ b/source-android/androidnative.pri/cpp/AndroidNative/environment.h @@ -0,0 +1,17 @@ +#ifndef ENVIRONMENT_H +#define ENVIRONMENT_H + +#include + +namespace AndroidNative { + + namespace Environment + { + extern QString DIRECTORY_DCIM; + + QString getExternalStoragePublicDirectory(const QString& path); + }; + +} + +#endif // ENVIRONMENT_H diff --git a/source-android/androidnative.pri/cpp/AndroidNative/mediascannerconnection.cpp b/source-android/androidnative.pri/cpp/AndroidNative/mediascannerconnection.cpp new file mode 100644 index 0000000..66b3eea --- /dev/null +++ b/source-android/androidnative.pri/cpp/AndroidNative/mediascannerconnection.cpp @@ -0,0 +1,16 @@ +#include "mediascannerconnection.h" +#include + +static bool loadedClass = false; + +void AndroidNative::MediaScannerConnection::scanFile(const QString &path) +{ + if (!loadedClass) { + SystemDispatcher::instance()->loadClass("androidnative.MediaScanner"); + loadedClass = true; + } + + QVariantMap map; + map["path"] = path; + SystemDispatcher::instance()->dispatch("androidnative.MediaScanner.scanFile", map); +} diff --git a/source-android/androidnative.pri/cpp/AndroidNative/mediascannerconnection.h b/source-android/androidnative.pri/cpp/AndroidNative/mediascannerconnection.h new file mode 100644 index 0000000..2929e7d --- /dev/null +++ b/source-android/androidnative.pri/cpp/AndroidNative/mediascannerconnection.h @@ -0,0 +1,14 @@ +#ifndef MEDIASCANNERCONNECTION_H +#define MEDIASCANNERCONNECTION_H + +#include + +namespace AndroidNative { + + namespace MediaScannerConnection + { + void scanFile(const QString& path); + } +} + +#endif // MEDIASCANNERCONNECTION_H diff --git a/source-android/androidnative.pri/cpp/AndroidNative/priv/androidnativeqmltypes.cpp b/source-android/androidnative.pri/cpp/AndroidNative/priv/androidnativeqmltypes.cpp new file mode 100644 index 0000000..4996192 --- /dev/null +++ b/source-android/androidnative.pri/cpp/AndroidNative/priv/androidnativeqmltypes.cpp @@ -0,0 +1,26 @@ +#include +#include +#include + +using namespace AndroidNative; + +static QObject *systemDispatcherProvider(QQmlEngine *engine, QJSEngine *scriptEngine) { + Q_UNUSED(engine); + Q_UNUSED(scriptEngine); + + SystemDispatcherProxy* object = new SystemDispatcherProxy(); + + return object; +} + + + +static void regiserQmlTypes() { + // QADevice is a exception. Won't register by QAQmlTypes. + + qmlRegisterSingletonType("AndroidNative", 1, 0, + "SystemDispatcher", + systemDispatcherProvider); +} + +Q_COREAPP_STARTUP_FUNCTION(regiserQmlTypes) diff --git a/source-android/androidnative.pri/cpp/AndroidNative/priv/systemdispatcherproxy.cpp b/source-android/androidnative.pri/cpp/AndroidNative/priv/systemdispatcherproxy.cpp new file mode 100644 index 0000000..bb0695f --- /dev/null +++ b/source-android/androidnative.pri/cpp/AndroidNative/priv/systemdispatcherproxy.cpp @@ -0,0 +1,25 @@ +#include +#include "systemdispatcherproxy.h" +#include "AndroidNative/systemdispatcher.h" + +AndroidNative::SystemDispatcherProxy::SystemDispatcherProxy(QObject *parent) : QObject(parent) +{ + connect(SystemDispatcher::instance(),SIGNAL(dispatched(QString,QVariantMap)), + this,SIGNAL(dispatched(QString,QVariantMap))); + +} + +AndroidNative::SystemDispatcherProxy::~SystemDispatcherProxy() +{ + +} + +void AndroidNative::SystemDispatcherProxy::dispatch(QString type, QVariantMap message) +{ + SystemDispatcher::instance()->dispatch(type,message); +} + +void AndroidNative::SystemDispatcherProxy::loadClass(QString className) +{ + SystemDispatcher::instance()->loadClass(className); +} diff --git a/source-android/androidnative.pri/cpp/AndroidNative/priv/systemdispatcherproxy.h b/source-android/androidnative.pri/cpp/AndroidNative/priv/systemdispatcherproxy.h new file mode 100644 index 0000000..4fb07ad --- /dev/null +++ b/source-android/androidnative.pri/cpp/AndroidNative/priv/systemdispatcherproxy.h @@ -0,0 +1,23 @@ +#pragma once + +#include +#include + +namespace AndroidNative { + + class SystemDispatcherProxy : public QObject + { + Q_OBJECT + public: + explicit SystemDispatcherProxy(QObject *parent = 0); + ~SystemDispatcherProxy(); + + Q_INVOKABLE void dispatch(QString type, QVariantMap message = QVariantMap()); + + Q_INVOKABLE void loadClass(QString className); + + signals: + void dispatched(QString type , QVariantMap message); + + }; +} diff --git a/source-android/androidnative.pri/cpp/AndroidNative/systemdispatcher.cpp b/source-android/androidnative.pri/cpp/AndroidNative/systemdispatcher.cpp new file mode 100644 index 0000000..008b154 --- /dev/null +++ b/source-android/androidnative.pri/cpp/AndroidNative/systemdispatcher.cpp @@ -0,0 +1,373 @@ +// Author: Ben Lau (https://github.com/benlau) +#include +#include +#include +#include +#include +#include "systemdispatcher.h" + +using namespace AndroidNative; + +static QPointer m_instance; + +QString SystemDispatcher::ACTIVITY_RESUME_MESSAGE = "Activity.onResume"; +QString SystemDispatcher::ACTIVITY_RESULT_MESSAGE = "Activity.onActivityResult"; +static bool registerNativesCalled = false; + +#ifdef Q_OS_ANDROID +#include +#include + +#define JCLASS_Name "androidnative/SystemDispatcher" +#define DISPATCH_SIGNATURE "(Ljava/lang/String;Ljava/util/Map;)V" +#define EMIT_SIGNATURE "(Ljava/lang/String;Ljava/util/Map;)V" + +static QVariantMap createVariantMap(jobject data); +static jobject createHashMap(const QVariantMap &data); + +static QVariant convertToQVariant(QAndroidJniObject value) { + QVariant v; + if (!value.isValid()) { + return v; + } + + QAndroidJniEnvironment env; + + jclass jclass_of_string = env->FindClass("java/lang/String"); + jclass jclass_of_integer = env->FindClass("java/lang/Integer"); + jclass jclass_of_boolean = env->FindClass("java/lang/Boolean"); + jclass jclass_of_list = env->FindClass("java/util/List"); + jclass jclass_of_map = env->FindClass("java/util/Map"); + + if (env->IsInstanceOf(value.object(),jclass_of_boolean)) { + v = QVariant::fromValue(value.callMethod("booleanValue","()Z")); + } else if (env->IsInstanceOf(value.object(),jclass_of_integer)) { + v = value.callMethod("intValue","()I"); + } else if (env->IsInstanceOf(value.object(),jclass_of_string)) { + v = value.toString(); + } else if (env->IsInstanceOf(value.object(), jclass_of_map)) { + v = createVariantMap(value.object()); + } else if (env->IsInstanceOf(value.object(),jclass_of_list)) { + QVariantList list; + int count = value.callMethod("size","()I"); + for (int i = 0 ; i < count ; i++) { + QAndroidJniObject item = value.callObjectMethod("get","(I)Ljava/lang/Object;",i); + list.append(convertToQVariant(item)); + } + v = list; + } + + env->DeleteLocalRef(jclass_of_string); + env->DeleteLocalRef(jclass_of_integer); + env->DeleteLocalRef(jclass_of_boolean); + env->DeleteLocalRef(jclass_of_list); + env->DeleteLocalRef(jclass_of_map); + + return v; +} + +static QVariantMap createVariantMap(jobject data) { + QVariantMap res; + + QAndroidJniEnvironment env; + /* Reference : https://community.oracle.com/thread/1549999 */ + + // Get the HashMap Class + jclass jclass_of_hashmap = (env)->GetObjectClass(data); + + // Get link to Method "entrySet" + jmethodID entrySetMethod = (env)->GetMethodID(jclass_of_hashmap, "entrySet", "()Ljava/util/Set;"); + + // Invoke the "entrySet" method on the HashMap object + jobject jobject_of_entryset = env->CallObjectMethod(data, entrySetMethod); + + // Get the Set Class + jclass jclass_of_set = (env)->FindClass("java/util/Set"); // Problem during compilation !!!!! + + if (jclass_of_set == 0) { + qWarning() << "java/util/Set lookup failed\n"; + return res; + } + + // Get link to Method "iterator" + jmethodID iteratorMethod = env->GetMethodID(jclass_of_set, "iterator", "()Ljava/util/Iterator;"); + + // Invoke the "iterator" method on the jobject_of_entryset variable of type Set + jobject jobject_of_iterator = env->CallObjectMethod(jobject_of_entryset, iteratorMethod); + + // Get the "Iterator" class + jclass jclass_of_iterator = (env)->FindClass("java/util/Iterator"); + + // Get link to Method "hasNext" + jmethodID hasNextMethod = env->GetMethodID(jclass_of_iterator, "hasNext", "()Z"); + + jmethodID nextMethod = env->GetMethodID(jclass_of_iterator, "next", "()Ljava/lang/Object;"); + + while (env->CallBooleanMethod(jobject_of_iterator, hasNextMethod) ) { + jobject jEntry = env->CallObjectMethod(jobject_of_iterator,nextMethod); + QAndroidJniObject entry = QAndroidJniObject(jEntry); + QAndroidJniObject key = entry.callObjectMethod("getKey","()Ljava/lang/Object;"); + QAndroidJniObject value = entry.callObjectMethod("getValue","()Ljava/lang/Object;"); + QString k = key.toString(); + + QVariant v = convertToQVariant(value); + + env->DeleteLocalRef(jEntry); + + if (v.isNull()) { + continue; + } + + res[k] = v; + } + + if (env->ExceptionOccurred()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + } + + env->DeleteLocalRef(jclass_of_hashmap); + env->DeleteLocalRef(jobject_of_entryset); + env->DeleteLocalRef(jclass_of_set); + env->DeleteLocalRef(jobject_of_iterator); + env->DeleteLocalRef(jclass_of_iterator); + + return res; +} + +static jobject convertToJObject(QVariant v) { + jobject res = 0; + QAndroidJniEnvironment env; + + if (v.type() == QVariant::String) { + QString str = v.toString(); + res = env->NewStringUTF(str.toLocal8Bit().data()); + } else if (v.type() == QVariant::Int) { + jclass integerClass = env->FindClass("java/lang/Integer"); + jmethodID integerConstructor = env->GetMethodID(integerClass, "", "(I)V"); + + res = env->NewObject(integerClass,integerConstructor,v.toInt()); + + env->DeleteLocalRef(integerClass); + } else if (v.type() == QVariant::Bool) { + jclass booleanClass = env->FindClass("java/lang/Boolean"); + jmethodID booleanConstructor = env->GetMethodID(booleanClass,"","(Z)V"); + + res = env->NewObject(booleanClass,booleanConstructor,v.toBool()); + + env->DeleteLocalRef(booleanClass); + + } else if (v.type() == QVariant::Map) { + res = createHashMap(v.toMap()); + } else if (v.type() == QVariant::List){ + QVariantList list = v.value(); + jclass arrayListClass = env->FindClass("java/util/ArrayList"); + jmethodID init = env->GetMethodID(arrayListClass, "", "(I)V"); + res = env->NewObject( arrayListClass, init, list.size()); + + jmethodID add = env->GetMethodID( arrayListClass, "add", + "(Ljava/lang/Object;)Z"); + + for (int i = 0 ; i < list.size() ; i++) { + jobject item = convertToJObject(list.at(i)); + env->CallBooleanMethod(res,add, item); + env->DeleteLocalRef(item); + } + + env->DeleteLocalRef(arrayListClass); + } else { + qWarning() << "ANSystemDispatcher: Non-supported data type - " << v.type(); + } + return res; +} + +static jobject createHashMap(const QVariantMap &data) { + QAndroidJniEnvironment env; + + jclass mapClass = env->FindClass("java/util/HashMap"); + + if (mapClass == NULL) { + qWarning() << "Failed to find class" << "java/util/HashMap"; + return NULL; + } + + jsize map_len = data.size(); + + jmethodID init = env->GetMethodID(mapClass, "", "(I)V"); + jobject hashMap = env->NewObject( mapClass, init, map_len); + + jmethodID put = env->GetMethodID( mapClass, "put", + "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); + + QMapIterator iter(data); + while (iter.hasNext()) { + iter.next(); + + QString key = iter.key(); + jstring jkey = env->NewStringUTF(key.toLocal8Bit().data()); + QVariant v = iter.value(); + jobject item = convertToJObject(v); + + if (item == 0) { + continue; + } + + env->CallObjectMethod(hashMap,put,jkey,item); + env->DeleteLocalRef(item); + env->DeleteLocalRef(jkey); + } + + if (env->ExceptionOccurred()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + } + + env->DeleteLocalRef(mapClass); + + return hashMap; +} + +static void jniEmit(JNIEnv* env,jobject object,jstring name,jobject data) { + Q_UNUSED(object); + Q_UNUSED(env); + + QAndroidJniObject tmp(name); + QString str = tmp.toString(); + + QVariantMap map; + + if (data != 0) { + map = createVariantMap(data); + } + + if (m_instance.isNull()) { + return; + } + + QMetaObject::invokeMethod(m_instance.data(),"dispatched",Qt::AutoConnection, + Q_ARG(QString, str), + Q_ARG(QVariantMap,map)); +} + +static void printInstruction() { + static bool printOnce = false; + + if (printOnce) { + return; + } + printOnce = true; + + // BuildMyString.com generated code. Please enjoy your string responsibly. + + QString msg = "Using SystemDispatcher in Android but SystemDispatcher::registerNatives() is never called. Instruction: \r\n" + "https://github.com/benlau/androidnative.pri/blob/master/docs/installation.md\r\n"; + + qWarning() << msg; +} +#endif + +AndroidNative::SystemDispatcher::SystemDispatcher(QObject* parent) : QObject(parent) +{ +} + +AndroidNative::SystemDispatcher::~SystemDispatcher() +{ +} + +AndroidNative::SystemDispatcher *SystemDispatcher::instance() +{ + if (!m_instance) { + QCoreApplication* app = QCoreApplication::instance(); + m_instance = new SystemDispatcher(app); + } + return m_instance; +} + +void AndroidNative::SystemDispatcher::dispatch(QString type, QVariantMap message) +{ + Q_UNUSED(type); + Q_UNUSED(message); + +#ifdef Q_OS_ANDROID + if (!registerNativesCalled) { + printInstruction(); + } + + QAndroidJniEnvironment env; + + jstring jType = env->NewStringUTF(type.toLocal8Bit().data()); + jobject jData = createHashMap(message); + QAndroidJniObject::callStaticMethod(JCLASS_Name, "dispatch", + DISPATCH_SIGNATURE, + jType,jData); + env->DeleteLocalRef(jType); + env->DeleteLocalRef(jData); + +#else + static bool dispatching = false; + static QQueue > queue; + + + if (dispatching) { + queue.enqueue(QPair (type,message) ); + return; + } + + dispatching = true; + emit dispatched(type,message); + + while (queue.size() > 0) { + QPair pair = queue.dequeue(); + emit dispatched(pair.first,pair.second); + } + dispatching = false; +#endif +} + +void AndroidNative::SystemDispatcher::loadClass(QString javaClassName) +{ + QVariantMap message; + message["className"] = javaClassName; + + dispatch("androidnative.SystemDispatcher.loadClass",message); +} + +void AndroidNative::SystemDispatcher::registerNatives() +{ + Q_UNUSED(registerNativesCalled); + +#ifdef Q_OS_ANDROID + registerNativesCalled = true; + + QAndroidJniEnvironment env; + jclass clazz = env->FindClass(JCLASS_Name); + if (!clazz) + { + qCritical() << "androidNative.SystemDispatcher Java class is not found. Please configure your build.gradle according to this instruction: \r\n" + "https://github.com/benlau/androidnative.pri/blob/master/docs/installation.md\r\n"; + if (env->ExceptionOccurred()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + } + return; + } + + JNINativeMethod methods[] = + { + {"jniEmit", EMIT_SIGNATURE, (void *)&jniEmit}, + }; + + int numMethods = sizeof(methods) / sizeof(methods[0]); + if (env->RegisterNatives(clazz, methods, numMethods) < 0) { + if (env->ExceptionOccurred()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + qCritical() << "Exception occurred!!!"; + return; + } + } + + QAndroidJniObject::callStaticMethod(JCLASS_Name, "init", + "()V"); +#endif +} diff --git a/source-android/androidnative.pri/cpp/AndroidNative/systemdispatcher.h b/source-android/androidnative.pri/cpp/AndroidNative/systemdispatcher.h new file mode 100644 index 0000000..a4e1a4c --- /dev/null +++ b/source-android/androidnative.pri/cpp/AndroidNative/systemdispatcher.h @@ -0,0 +1,50 @@ +// Author: Ben Lau (https://github.com/benlau) +#pragma once +#include +#include + +namespace AndroidNative { + + /// SystemDispatcher provides an simple messaging interface between C/C++/QML and Java code. + + class SystemDispatcher : public QObject + { + Q_OBJECT + public: + ~SystemDispatcher(); + static SystemDispatcher* instance(); + + /// Dispatch a message via Dispatcher + /** The message will be first passed to Java's SystemDispatcher and invoke + * registered listener. Once it is finished, it will emit the + * "dispatched" signal. + * + */ + Q_INVOKABLE void dispatch(QString type , QVariantMap message = QVariantMap()); + + /// Load a Java class + /** It will dispatch a message to Java and let it to load a Java class. That + * will force to run code in static block. + * + */ + Q_INVOKABLE void loadClass(QString javaClassName); + + /// Register JNI native methods. This function must be called in JNI_OnLoad. Otherwise, the messenger will not be working + static void registerNatives(); + + /// The name of message that will be dispatched during Activity.onActivityResult. + static QString ACTIVITY_RESULT_MESSAGE; + + /// The name of message that will be dispatched during Activity.onResume. + static QString ACTIVITY_RESUME_MESSAGE; + + signals: + /// The signal is emitted when a message is dispatched. + void dispatched(QString type , QVariantMap message); + + private: + explicit SystemDispatcher(QObject* parent = 0); + + }; + +} diff --git a/source-android/androidnative.pri/docs/System Dispatcher - Sequence Diagram.png b/source-android/androidnative.pri/docs/System Dispatcher - Sequence Diagram.png new file mode 100644 index 0000000..7bf962c Binary files /dev/null and b/source-android/androidnative.pri/docs/System Dispatcher - Sequence Diagram.png differ diff --git a/source-android/androidnative.pri/docs/index.qdoc b/source-android/androidnative.pri/docs/index.qdoc new file mode 100644 index 0000000..1c9d001 --- /dev/null +++ b/source-android/androidnative.pri/docs/index.qdoc @@ -0,0 +1,64 @@ +/*! + \page index.html + \title AndroidNative Project + +UI Components + + \list + \li \l ActionBar + \li \l BottomSheet + \li \l Button + \li \l Dialog + \li \l DropDownMenu + \li \l FloatingActionButton + \li \l Ink + \li \l ListItem + \li \l MaterialShadow + \li \l Page + \li \l PageStack + \li \l Paper + \li \l Popup + \li \l TabBar + \li \l TabView + \li \l Text + \li \l TextField + \endlist + +Singleton Components + \list + \li \l A + \li \l Device + \li \l Constants + \endlist + +Native Components + \list + \li \l ImagePicker + \endlist + +Utility Components + \list + \li \l InverseMouseArea + \li \l RectToRectMatrix + \endlist + + +Styles + \list + \li \l ActionBarMaterial + \li \l ButtonMaterial + \li \l DialogMaterial + \li \l DropDownMenuMaterial + \li \l FloatingActionButtonMaterial + \li \l ListItemMaterial + \li \l Material + \li \l PageMaterial + \li \l RaisedButtonMaterial + \li \l TabBarMaterial + \li \l TextFieldMaterial + \li \l TextMaterial + \li \l Theme + \li \l ThemeManager + \endlist + + */ diff --git a/source-android/androidnative.pri/docs/installation.md b/source-android/androidnative.pri/docs/installation.md new file mode 100644 index 0000000..a85781b --- /dev/null +++ b/source-android/androidnative.pri/docs/installation.md @@ -0,0 +1,88 @@ +AndroidNative Installation Guide +================================ + +Step 1 - Download source package +----------------------------- + +It is recommended to install AndroidNative via qpm + + qpm install android.native.pri + +Step 2 - Setup import path [Optional] +--------------------------- + +In case, you are using Qt <= 5.6 , you need to add the import path manually + + engine.addImportPath("qrc:/qt-project.org/imports"); + +Step 3 - JNI_OnLoad +------------------- + +In you main.cpp, add following lines: + +``` +#ifdef Q_OS_ANDROID +#include +#include +#include + +JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*) { + Q_UNUSED(vm); + qDebug("NativeInterface::JNI_OnLoad()"); + + // It must call this function within JNI_OnLoad to enable System Dispatcher + AndroidNative::SystemDispatcher::registerNatives(); + + return JNI_VERSION_1_6; +} +#endif +``` + +Example: [main.cpp](https://github.com/benlau/androidnative.pri/blob/master/examples/androidnativeexample/main.cpp#L18) + +Step 4 - Modify build.gradle +---------------------------- + +AndroidNative only supports gradle build system, and you must have AndroidManifest.xml and build.gradle file is generated. If you don't know how to do, please check the document below for "Create templates" + +[Deploying Applications to Android Devices | Qt Creator Manual](http://doc.qt.io/qtcreator/creator-deploying-android.html) + +1) Copy [androidnative.gradle](https://github.com/benlau/androidnative.pri/blob/master/examples/androidnativeexample/android-sources/androidnative.gradle) to ANDROID_PACKAGE_SOURCE_DIR + +2) Add the following lines **at the end** of your build.gradle + +``` + apply from: "androidnative.gradle" + setAndroidNativePath("/../vendor/android/native/pri") +``` + +The input argument of `setAndroidNativePath` is the relative path from the ANDROID_PACKAGE_SOURCE_DIR to the installation path of AndroidNative (the folder contains `androidnative.pri`). You need to modify it in case your AndroidNative is not installed via qpm or the ANDROID_PACKAGE_SOURCE_DIR is not set to the default path. + +Example: [build.gradle](https://github.com/benlau/androidnative.pri/blob/master/examples/androidnativeexample/android-sources/build.gradle#L59) + +Step 5 - Modify your Android activity [Optional] +------------------------------------------------ + +*If you don't need to use feature like ImagePicker, you may skip this step.* + +If you don't have your own custom Android activity, modify AndroidManifest.xml, change activity.name to "androidnative.AndroidnativeActivity" + +Example: [AndroidManifest.xml](https://github.com/benlau/androidnative.pri/blob/master/examples/androidnativeexample/android-sources/AndroidManifest.xml) + +If you have your own custom Android activity, add following lines to your activity class: + +``` +import androidnative.SystemDispatcher; +``` + +``` +@Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + SystemDispatcher.onActivityResult(requestCode,resultCode,data); + } +``` + +Example: [AndroidNativeActivity.java](https://github.com/benlau/androidnative.pri/blob/master/java/src/androidnative/AndroidNativeActivity.java) + + diff --git a/source-android/androidnative.pri/docs/quickandroid.qdocconf b/source-android/androidnative.pri/docs/quickandroid.qdocconf new file mode 100644 index 0000000..2d32994 --- /dev/null +++ b/source-android/androidnative.pri/docs/quickandroid.qdocconf @@ -0,0 +1,22 @@ +project = AndroidNative +url = https://github.com/benlau/quickandroid +description = Qt's Material Design and Support Library for Android +sourcedirs = ./ +sourcedirs += ../qml/AndroidNative +sourcedirs += ../ +exampledirs += ../examples/quickandroidexample/ +sources.fileextensions = "*.qml *.qdoc *.cpp" +headers.fileextensions = "*.h" +version = 1.0 +syntaxhighlighting = true +sourceencoding = UTF-8 +outputencoding = UTF-8 +outputdir = html +outputformats = HTML + +HTML.templatedir = . +HTML.stylesheets = $$QT_INSTALL_DOCS/global/html/style/offline.css + +HTML.headerstyles = \ + " \n" + diff --git a/source-android/androidnative.pri/docs/screenshots/example1.png b/source-android/androidnative.pri/docs/screenshots/example1.png new file mode 100644 index 0000000..51141ce Binary files /dev/null and b/source-android/androidnative.pri/docs/screenshots/example1.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/Components.qml b/source-android/androidnative.pri/examples/androidnativeexample/Components.qml new file mode 100644 index 0000000..cdd7880 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/Components.qml @@ -0,0 +1,62 @@ +import QtQuick 2.2 +import QtQuick.Window 2.1 +import QuickAndroid 0.1 +import QuickAndroid.Styles 0.1 +import "./theme" + +Page { + objectName: "ComponentPage"; + + property var pages: [ + { + name: "Image Picker", + demo: "imagePicker/ImagePickerDemo.qml", + description: "Pick photo via Java language binding" + },{ + name: "Toast", + demo: "toast/ToastDemo.qml", + description: "Toast Demonstration" + },{ + name: "Notification", + demo: "notification/NotificationDemo.qml", + description: "Demonstrate how to use SystemDispatcher to send notification" + },{ + name: "Information", + demo: "info/InfoDemo.qml", + description: "Android System Information" + },{ + name: "Status Bar", + demo: "statusbar/StatusBarDemo.qml", + description: "Config Status Bar" + } + + ]; + + actionBar: ActionBar { + id : actionBar + iconSource: A.drawable("ic_menu",Constants.black87) + title: "AndroidNative Component List" + showIcon: false + actionButtonEnabled: false + } + + VisualDataModel { + id: visualDataModel + delegate: ListItem { + title: modelData.name + subtitle: modelData.description + onClicked: { + present(Qt.resolvedUrl(modelData.demo)); + } + } + + model: pages; + } + + ListView { + anchors.fill: parent + + model : visualDataModel + } + +} diff --git a/source-android/androidnative.pri/examples/androidnativeexample/README.md b/source-android/androidnative.pri/examples/androidnativeexample/README.md new file mode 100644 index 0000000..e3a9f38 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/README.md @@ -0,0 +1,25 @@ +AndroidNative Example Program +===================== + +Prerequisites +------------- + + * Qt Android SDK >= 5.6 + * Android SDK + +Check this article for how to setup Qt and Android SDK: + +[Getting Started with Qt for Android](http://qt-project.org/doc/qt-5/androidgs.html) + +Build Instruction +----------------- + + 1. Run `qpm install` to get required packages + 1. Open androidnativeexample.pro by Qt Creator + 1. Press the "Projects" tab. Make sure the "Android for xxx" kit has been selected + 1. Plug a Android device to your computer + 1. Press "Build" -> "Run" + 1. The program will be deployed to your device. It is so easy! + +![Screenshot](https://raw.githubusercontent.com/benlau/androidnative.pri/master/docs/screenshots/example1.png) + diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/AndroidManifest.xml b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/AndroidManifest.xml new file mode 100644 index 0000000..5ecf270 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/AndroidManifest.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/androidnative.gradle b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/androidnative.gradle new file mode 100644 index 0000000..8fe9786 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/androidnative.gradle @@ -0,0 +1,34 @@ + +// Obtain androidPackageSourceDir +// androidPackageSourceDir is the absolute path of the folder containing build.gradle and AndroidManifests.xml +// This code also works with androiddeployqt. + +import groovy.json.JsonSlurper + +String getAndroidPackageSourceDir() { + String res = System.getProperty("user.dir"); + + FileTree tree = fileTree(dir: res + "/..").include("android*deployment-settings.json"); + + if (tree.getFiles().size() > 0) { + def inputFile = tree.getFiles().toArray()[0]; + def InputJSON = new JsonSlurper().parseText(inputFile.text); + res = InputJSON["android-package-source-directory"] + } else { + println("android*deployment-settings.json not found. Set androidPackageSourceDir to user.dir"); + } + + return res; +} + +String setAndroidNativePath(String path) { + String androidPackageSourceDir = getAndroidPackageSourceDir(); + String androidNativePath = androidPackageSourceDir + path + "/java/src"; + LinkedHashSet hash = android.sourceSets.main.java.srcDirs; + hash.add(androidNativePath); + android.sourceSets.main.java.srcDirs = hash; +} + +ext { + setAndroidNativePath = this.&setAndroidNativePath; +} diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/build.gradle b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/build.gradle new file mode 100644 index 0000000..4ce7902 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/build.gradle @@ -0,0 +1,60 @@ + +buildscript { + repositories { + jcenter() + } + + dependencies { + classpath 'com.android.tools.build:gradle:1.3.0' + } +} + +allprojects { + repositories { + jcenter() + } +} + +apply plugin: 'com.android.application' + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) +} + +android { + /******************************************************* + * The following variables: + * - androidBuildToolsVersion, + * - androidCompileSdkVersion + * - qt5AndroidDir - holds the path to qt android files + * needed to build any Qt application + * on Android. + * + * are defined in gradle.properties file. This file is + * updated by QtCreator and androiddeployqt tools. + * Changing them manually might break the compilation! + *******************************************************/ + + compileSdkVersion androidCompileSdkVersion.toInteger() + + buildToolsVersion androidBuildToolsVersion + + sourceSets { + main { + manifest.srcFile 'AndroidManifest.xml' + java.srcDirs = [qt5AndroidDir + '/src', 'src', 'java'] + aidl.srcDirs = [qt5AndroidDir + '/src', 'src', 'aidl'] + res.srcDirs = [qt5AndroidDir + '/res', 'res'] + resources.srcDirs = ['src'] + renderscript.srcDirs = ['src'] + assets.srcDirs = ['assets'] + jniLibs.srcDirs = ['libs'] + } + } + lintOptions { + abortOnError false + } +} + +apply from: "androidnative.gradle" +setAndroidNativePath("/../../.."); diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradle.properties b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradle.properties new file mode 100644 index 0000000..798b77d --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradle.properties @@ -0,0 +1,9 @@ +## This file is automatically generated by QtCreator. +# +# This file must *NOT* be checked into Version Control Systems, +# as it contains information specific to your local configuration. + +androidBuildToolsVersion=25.0.3 +androidCompileSdkVersion=25 +buildDir=.build +qt5AndroidDir=/home/pankraz/Qt/5.9.1/android_armv7/src/android/java diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradle.properties~ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradle.properties~ new file mode 100644 index 0000000..798b77d --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradle.properties~ @@ -0,0 +1,9 @@ +## This file is automatically generated by QtCreator. +# +# This file must *NOT* be checked into Version Control Systems, +# as it contains information specific to your local configuration. + +androidBuildToolsVersion=25.0.3 +androidCompileSdkVersion=25 +buildDir=.build +qt5AndroidDir=/home/pankraz/Qt/5.9.1/android_armv7/src/android/java diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradle/wrapper/gradle-wrapper.jar b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..13372ae Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradle/wrapper/gradle-wrapper.jar differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradle/wrapper/gradle-wrapper.properties b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9f2bca4 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Feb 16 01:04:18 HKT 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.2-all.zip diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradlew b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradlew new file mode 100755 index 0000000..9d82f78 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradlew.bat b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradlew.bat new file mode 100644 index 0000000..aec9973 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/local.properties b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/local.properties new file mode 100644 index 0000000..4277a61 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/local.properties @@ -0,0 +1,6 @@ +## This file is automatically generated by QtCreator. +# +# This file must *NOT* be checked into Version Control Systems, +# as it contains information specific to your local configuration. + +sdk.dir=/home/pankraz/android-sdk_alt diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/local.properties~ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/local.properties~ new file mode 100644 index 0000000..4277a61 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/local.properties~ @@ -0,0 +1,6 @@ +## This file is automatically generated by QtCreator. +# +# This file must *NOT* be checked into Version Control Systems, +# as it contains information specific to your local configuration. + +sdk.dir=/home/pankraz/android-sdk_alt diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/res/drawable/icon.png b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/res/drawable/icon.png new file mode 100644 index 0000000..156243d Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/res/drawable/icon.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/res/drawable/splash.xml b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/res/drawable/splash.xml new file mode 100644 index 0000000..c1bd6fc --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/res/drawable/splash.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/res/values/apptheme.xml b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/res/values/apptheme.xml new file mode 100644 index 0000000..455b965 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/res/values/apptheme.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/res/values/libs.xml b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/res/values/libs.xml new file mode 100644 index 0000000..4d68673 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/res/values/libs.xml @@ -0,0 +1,25 @@ + + + + https://download.qt-project.org/ministro/android/qt5/qt-5.4 + + + + + + + + + + + + + + + + + + + + diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/src/ExampleActivity.java b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/src/ExampleActivity.java new file mode 100644 index 0000000..ffa8952 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/src/ExampleActivity.java @@ -0,0 +1,16 @@ +package androidnative.example; + +import androidnative.AndroidNativeActivity; + +/** + * Created by benlau on 8/3/2017. + */ + +public class ExampleActivity extends AndroidNativeActivity { + public ExampleActivity() { + super(); + + QT_ANDROID_THEMES = new String[] {""}; + QT_ANDROID_DEFAULT_THEME = ""; + } +} diff --git a/source-android/androidnative.pri/examples/androidnativeexample/android-sources/src/ExampleService.java b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/src/ExampleService.java new file mode 100644 index 0000000..082ff10 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/android-sources/src/ExampleService.java @@ -0,0 +1,96 @@ +package androidnative.example; +import androidnative.SystemDispatcher; +import android.app.Notification; +import android.app.NotificationManager; +import android.util.Log; +import android.os.Handler; +import android.app.Activity; +import android.view.View; +import android.content.Context; +import java.util.Map; +import org.qtproject.qt5.android.QtNative; + +public class ExampleService { + + static { + + SystemDispatcher.addListener(new SystemDispatcher.Listener() { + + NotificationManager m_notificationManager; + Notification.Builder m_builder; + + private void notificationManagerNotify(Map data) { + + final Activity activity = QtNative.activity(); + final Map messageData = data; + + Runnable runnable = new Runnable () { + public void run() { + try { + String title = (String) messageData.get("title"); + + String message = (String) messageData.get("message"); + + if (m_notificationManager == null) { + m_notificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE); + m_builder = new Notification.Builder(activity); + + // Small Icon is a must to make notification works. + // And that is why you need to inherit QtActivity + m_builder.setSmallIcon(R.drawable.icon); + } + + m_builder.setContentTitle(title); + m_builder.setContentText(message); + m_notificationManager.notify(1, m_builder.build()); + + // Test function. Remove it later. + SystemDispatcher.dispatch("Notifier.notifyFinished"); + } catch (Exception e) { + Log.d("",e.getMessage()); + } + + }; + }; + activity.runOnUiThread(runnable); + } + + private void hapticFeedbackPerform(Map data) { + + final Activity activity = QtNative.activity(); + final Map messageData = data; + Runnable runnable = new Runnable () { + public void run() { + int feedbackConstant = (Integer) messageData.get("feedbackConstant"); + int flags = (Integer) messageData.get("flags"); + + Log.d("",String.format("hapticFeedbackPerform(%d,%d)",feedbackConstant,flags)); + + View rootView = activity.getWindow().getDecorView().getRootView(); + rootView.performHapticFeedback(feedbackConstant, flags); + + // Test function. Remove it later. + SystemDispatcher.dispatch("hapticFeedbackPerformFinished"); + }; + }; + activity.runOnUiThread(runnable); + } + + public void onDispatched(String name , Map data) { + + if (name.equals("Notifier.notify")) { + notificationManagerNotify(data); + return; + } else if (name.equals("hapticFeedbackPerform")) { + hapticFeedbackPerform(data); + return; + } + + return; + } + }); + + } + +} + diff --git a/source-android/androidnative.pri/examples/androidnativeexample/androidnativeexample.pro b/source-android/androidnative.pri/examples/androidnativeexample/androidnativeexample.pro new file mode 100644 index 0000000..cec26e5 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/androidnativeexample.pro @@ -0,0 +1,38 @@ +TEMPLATE = app + +QT += qml quick + +SOURCES += main.cpp \ + debugwrapper.cpp + +RESOURCES += qml.qrc + +# Additional import path used to resolve QML modules in Qt Creator's code model +QML_IMPORT_PATH += ../.. + +android { + ANDROID_PACKAGE_SOURCE_DIR = $$PWD/android-sources +} + +# include(vendor/vendor.pri) +# Default rules for deployment. +include(deployment.pri) +include(../../androidnative.pri) +include(../../../../../../quickandroid/quickandroid.pri) + +DISTFILES += \ + android-sources/AndroidManifest.xml \ + android-sources/src/quickandroid/example/ExampleService.java \ + README.md \ + android-sources/gradle/wrapper/gradle-wrapper.jar \ + android-sources/gradlew \ + android-sources/res/values/libs.xml \ + android-sources/build.gradle \ + android-sources/gradle/wrapper/gradle-wrapper.properties \ + android-sources/gradlew.bat \ + android-sources/settings.gradle \ + android-sources/src/androidnative/example/ExampleService.java + +HEADERS += \ + ../../README.md \ + debugwrapper.h diff --git a/source-android/androidnative.pri/examples/androidnativeexample/androidnativeexample.pro.user b/source-android/androidnative.pri/examples/androidnativeexample/androidnativeexample.pro.user new file mode 100644 index 0000000..1693b53 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/androidnativeexample.pro.user @@ -0,0 +1,392 @@ + + + + + + EnvironmentId + {8825bc46-5cad-4a59-be78-bf9eeaa7217a} + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + false + true + + Cpp + + CppGlobal + + + + QmlJS + + QmlJSGlobal + + + 2 + UTF-8 + false + 4 + false + 80 + true + true + 1 + true + false + 0 + true + true + 0 + 8 + true + 1 + true + true + true + false + + + + ProjectExplorer.Project.PluginSettings + + + + ProjectExplorer.Project.Target.0 + + Android + Android + {8e3757e7-5698-4d0f-9f13-55359b1a832e} + 0 + 0 + 0 + + /home/pankraz/build/debug + + + true + qmake + + QtProjectManager.QMakeBuildStep + true + + false + false + false + + + true + Make + + Qt4ProjectManager.MakeStep + + -w + -r + + false + + + + + true + Anwendungsdaten kopieren + + Qt4ProjectManager.AndroidPackageInstallationStep + + + android-25 + + true + Android-APK erstellen + + QmakeProjectManager.AndroidBuildApkStep + 2 + true + false + + 4 + Build + + ProjectExplorer.BuildSteps.Build + + + + true + Make + + Qt4ProjectManager.MakeStep + + -w + -r + + true + clean + + + 1 + Bereinigen + + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + + Qt4ProjectManager.Qt4BuildConfiguration + 2 + true + + + /home/pankraz/ownCloud/clientsync/Friendiqa/v0.005/source-android/androidnative.pri/examples/build-androidnativeexample-Android-Release + + + true + qmake + + QtProjectManager.QMakeBuildStep + false + + false + false + false + + + true + Make + + Qt4ProjectManager.MakeStep + + -w + -r + + false + + + + + true + Anwendungsdaten kopieren + + Qt4ProjectManager.AndroidPackageInstallationStep + + + android-25 + + true + Android-APK erstellen + + QmakeProjectManager.AndroidBuildApkStep + 2 + true + false + + 4 + Build + + ProjectExplorer.BuildSteps.Build + + + + true + Make + + Qt4ProjectManager.MakeStep + + -w + -r + + true + clean + + + 1 + Bereinigen + + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + + Qt4ProjectManager.Qt4BuildConfiguration + 0 + true + + + /home/pankraz/ownCloud/clientsync/Friendiqa/v0.005/source-android/androidnative.pri/examples/build-androidnativeexample-Android-Profile + + + true + qmake + + QtProjectManager.QMakeBuildStep + true + + false + true + false + + + true + Make + + Qt4ProjectManager.MakeStep + + -w + -r + + false + + + + + true + Anwendungsdaten kopieren + + Qt4ProjectManager.AndroidPackageInstallationStep + + + android-25 + + true + Android-APK erstellen + + QmakeProjectManager.AndroidBuildApkStep + 2 + true + false + + 4 + Build + + ProjectExplorer.BuildSteps.Build + + + + true + Make + + Qt4ProjectManager.MakeStep + + -w + -r + + true + clean + + + 1 + Bereinigen + + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + + Qt4ProjectManager.Qt4BuildConfiguration + 0 + true + + 3 + + + + true + Deployment auf Android-Gerät + + Qt4ProjectManager.AndroidDeployQtStep + false + + 1 + Deployment + + ProjectExplorer.BuildSteps.Deploy + + 1 + Deployment auf Android-Gerät + Deployment auf Android-Gerät + Qt4ProjectManager.AndroidDeployConfiguration2 + + 1 + + CB5A22HSB9 + + + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + + + + androidnativeexample + + Qt4ProjectManager.AndroidRunConfiguration:/home/pankraz/ownCloud/clientsync/Friendiqa/v0.005/source-android/androidnative.pri/examples/androidnativeexample/androidnativeexample.pro + androidnativeexample.pro + 3768 + false + true + false + false + true + + 1 + + + + ProjectExplorer.Project.TargetCount + 1 + + + ProjectExplorer.Project.Updater.FileVersion + 18 + + + Version + 18 + + diff --git a/source-android/androidnative.pri/examples/androidnativeexample/debugwrapper.cpp b/source-android/androidnative.pri/examples/androidnativeexample/debugwrapper.cpp new file mode 100644 index 0000000..8aaf024 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/debugwrapper.cpp @@ -0,0 +1,17 @@ +#include "debugwrapper.h" +#include "AndroidNative/debug.h" + +DebugWrapper::DebugWrapper(QObject *parent) : QObject(parent) +{ + +} + +long DebugWrapper::getNativeHeapSize() const +{ + return AndroidNative::Debug::getNativeHeapSize(); +} + +long DebugWrapper::getNativeHeapAllocatedSize() const +{ + return AndroidNative::Debug::getNativeHeapAllocatedSize(); +} diff --git a/source-android/androidnative.pri/examples/androidnativeexample/debugwrapper.h b/source-android/androidnative.pri/examples/androidnativeexample/debugwrapper.h new file mode 100644 index 0000000..80c3424 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/debugwrapper.h @@ -0,0 +1,20 @@ +#ifndef DEBUGWRAPPER_H +#define DEBUGWRAPPER_H + +#include + +class DebugWrapper : public QObject +{ + Q_OBJECT +public: + explicit DebugWrapper(QObject *parent = 0); + +signals: + +public slots: + long getNativeHeapSize() const; + + long getNativeHeapAllocatedSize() const; +}; + +#endif // DEBUGWRAPPER_H diff --git a/source-android/androidnative.pri/examples/androidnativeexample/deployment.pri b/source-android/androidnative.pri/examples/androidnativeexample/deployment.pri new file mode 100644 index 0000000..5441b63 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/deployment.pri @@ -0,0 +1,27 @@ +android-no-sdk { + target.path = /data/user/qt + export(target.path) + INSTALLS += target +} else:android { + x86 { + target.path = /libs/x86 + } else: armeabi-v7a { + target.path = /libs/armeabi-v7a + } else { + target.path = /libs/armeabi + } + export(target.path) + INSTALLS += target +} else:unix { + isEmpty(target.path) { + qnx { + target.path = /tmp/$${TARGET}/bin + } else { + target.path = /opt/$${TARGET}/bin + } + export(target.path) + } + INSTALLS += target +} + +export(INSTALLS) diff --git a/source-android/androidnative.pri/examples/androidnativeexample/dialog/DialogDemo.qml b/source-android/androidnative.pri/examples/androidnativeexample/dialog/DialogDemo.qml new file mode 100644 index 0000000..8ee22be --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/dialog/DialogDemo.qml @@ -0,0 +1,38 @@ +import QtQuick 2.0 +import QuickAndroid 0.1 +import QuickAndroid.Styles 0.1 +import "../theme" + +Page { + actionBar: ActionBar { + id: actionBar + upEnabled: true + title: qsTr("Dialog Demo") + showTitle: true + + onActionButtonClicked: back(); + z: 10 + + } + + Button { + id: label + text : "Press to launch dialog" + anchors.centerIn: parent + onClicked: { + dialog.open(); + } + } + + Dialog { + id: dialog + anchors.centerIn: parent + title: "Dialog" + Text { + text: "Demo" + } + z: 20 + + acceptButtonText: "OK" + } +} diff --git a/source-android/androidnative.pri/examples/androidnativeexample/imagePicker/ImagePickerDemo.qml b/source-android/androidnative.pri/examples/androidnativeexample/imagePicker/ImagePickerDemo.qml new file mode 100644 index 0000000..e38c7a3 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/imagePicker/ImagePickerDemo.qml @@ -0,0 +1,77 @@ +import QtQuick 2.0 +import QuickAndroid 0.1 +import AndroidNative 1.0 as AN +import "../theme" + +Page { + id: demo + actionBar: ActionBar { + title: "Image Picker Demo" + onActionButtonClicked: back(); + } + + AN.ImagePicker { + id: imagePicker; + multiple : true + } + + Rectangle { + anchors.fill: parent + color: Constants.black100 + + Image { + id: image + anchors.fill: parent + source: imagePicker.imageUrl + fillMode: Image.PreserveAspectFit + visible: imagePicker.imageUrls.length <= 1 + } + + Grid { + columns: 3 + spacing: 0 + visible: !image.visible + + Repeater { + model: imagePicker.imageUrls + delegate: Image { + width: demo.width / 3 + height: width / 4 * 3 + source: modelData + asynchronous: true + fillMode: Image.PreserveAspectCrop + } + } + } + + Column { + anchors.right: parent.right + anchors.rightMargin: 16 * A.dp + anchors.bottom: parent.bottom + anchors.bottomMargin: 32 * A.dp + + spacing: 16 * A.dp + + FloatingActionButton { + iconSource: A.drawable("ic_camera",Constants.black87); + size: Constants.small + backgroundColor: Constants.white100 + onClicked: { + imagePicker.takePhoto(); + } + } + + FloatingActionButton { + iconSource: A.drawable("ic_image",Constants.black87); + size: Constants.small + backgroundColor: Constants.white100 + onClicked: { + imagePicker.pickImage(); + } + } + + } + + } +} + diff --git a/source-android/androidnative.pri/examples/androidnativeexample/info/InfoDemo.qml b/source-android/androidnative.pri/examples/androidnativeexample/info/InfoDemo.qml new file mode 100644 index 0000000..d86a319 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/info/InfoDemo.qml @@ -0,0 +1,55 @@ +import QtQuick 2.0 +import QuickAndroid 0.1 +import QuickAndroid.Styles 0.1 +import "../theme" + +Page { + id: page + actionBar: ActionBar { + id: actionBar + upEnabled: true + title: qsTr("Information") + showTitle: true + + onActionButtonClicked: back(); + z: 10 + } + + VisualItemModel { + id: itemModel + + ListItem { + title: "Environment.DIRECTORY_DCIM" + subtitle: Environment.DIRECTORY_DCIM + interactive: false + width: page.width + } + + ListItem { + title: "Debug.getNativeHeapSize" + subtitle: (Debug.getNativeHeapSize() / 1024 / 1024).toFixed(2) + "MB"; + interactive: false + width: page.width + } + + ListItem { + title: "Debug.getNativeHeapAllocatedSize" + subtitle: (Debug.getNativeHeapAllocatedSize() / 1024 / 1024).toFixed(2) + "MB"; + interactive: false + width: page.width + } + + ListItem { + title: "QThread.idealThreadCount" + subtitle: Misc.idealThreadCount; + interactive: false + width: page.width + } + } + + + ListView { + anchors.fill: parent + model: itemModel + } +} diff --git a/source-android/androidnative.pri/examples/androidnativeexample/main.cpp b/source-android/androidnative.pri/examples/androidnativeexample/main.cpp new file mode 100644 index 0000000..062572b --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/main.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include +#include +//#include "qadrawableprovider.h" +#include "AndroidNative/systemdispatcher.h" +#include "AndroidNative/environment.h" +#include "AndroidNative/debug.h" +#include "AndroidNative/mediascannerconnection.h" +#include "debugwrapper.h" + +using namespace AndroidNative; + +#ifdef Q_OS_ANDROID +#include +#include + +JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*) { + Q_UNUSED(vm); + qDebug("NativeInterface::JNI_OnLoad()"); + + // It must call this function within JNI_OnLoad to enable System Dispatcher + SystemDispatcher::registerNatives(); + return JNI_VERSION_1_6; +} +#endif + +int main(int argc, char *argv[]) +{ +#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) + QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); +#endif + + QGuiApplication app(argc, argv); + app.setApplicationName("Android Native Example"); + app.setOrganizationDomain("com.github.benlau.androidnative"); + + QSettings settings; + + settings.setValue("firstTimeLoading", false); + settings.sync(); + + QVariantMap env; + env["DIRECTORY_DCIM"] = Environment::getExternalStoragePublicDirectory(Environment::DIRECTORY_DCIM); + + QVariantMap misc; + misc["idealThreadCount"] = QThread::idealThreadCount(); + + MediaScannerConnection::scanFile(""); + + SystemDispatcher::instance()->loadClass("androidnative.example.ExampleService"); + + QQmlApplicationEngine engine; + + /* QuickAndroid Initialization */ + engine.addImportPath("qrc:///"); // Add QuickAndroid into the import path + engine.rootContext()->setContextProperty("Environment", env); + engine.rootContext()->setContextProperty("Misc", misc); + engine.rootContext()->setContextProperty("Debug", new DebugWrapper(&engine)); + + /* End of QuickAndroid Initialization */ + + // Extra features: + //QADrawableProvider* provider = new QADrawableProvider(); + //provider->setBasePath("qrc://res"); + //engine.addImageProvider("drawable",provider); + engine.load(QUrl(QStringLiteral("qrc:///main.qml"))); + + return app.exec(); +} diff --git a/source-android/androidnative.pri/examples/androidnativeexample/main.qml b/source-android/androidnative.pri/examples/androidnativeexample/main.qml new file mode 100644 index 0000000..9a08956 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/main.qml @@ -0,0 +1,76 @@ +import QtQuick 2.2 +import QtQuick.Window 2.2 +import QuickAndroid 0.1 +import QuickAndroid.Styles 0.1 +import "./theme" + +Window { + id: window; + width: 480 + height: 640 + + color: "#FFFFFF" + + visible: false; + + /* Fast Splash Screen Setup Instruction + + 1. Create a custom theme (apptheme.qml) and set windowBackground to @drawable/splash.xml (Your splash screen drawable) + + 2. Within AndroidManifest.xml, set android.app.splash_screen_drawable to @drawable/splash.xml + + + + + + That will show a splash screen while Qt is loading. However, screen flicker will happen when your Window + item is shown. To prevent screen flicker completely, you could setup your main.qml accoroding to step 3. + + 3. In your main.qml (the one with Window component) + + 3.1. Set Window.color to a color which is similar to splash screen / Theme.windowBackground + + 3.2. Set visible of Window to false until your content is loaded. (Keep Android splash screen while loading) + + 3.3. Use an asynchronous Loader for your content. Set opacity to 0. + + 3.4. Once everything is ready, set Window.visible to true and perform a fade-in animation on Loader + + */ + + Loader { + id: loader + parent: null + width: window.width + height: window.height + asynchronous: true + opacity: 0 + focus: true; + + sourceComponent: PageStack { + id: stack + objectName: "PageStack"; + initialPage: Components { + + onPresented: { + window.visible = true; + A.setTimeout(function() { + loader.parent = window.contentItem; + loader.opacity = 1; + }, 34); + } + } + } + + Behavior on opacity { + NumberAnimation { + duration: 200 + easing.type: Easing.OutQuad; + } + } + } + + Component.onCompleted: { + ThemeManager.currentTheme = AppTheme + } +} diff --git a/source-android/androidnative.pri/examples/androidnativeexample/notification/NotificationDemo.qml b/source-android/androidnative.pri/examples/androidnativeexample/notification/NotificationDemo.qml new file mode 100644 index 0000000..174a5a0 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/notification/NotificationDemo.qml @@ -0,0 +1,30 @@ +import QtQuick 2.2 +import QtQuick.Window 2.1 +import QuickAndroid 0.1 +import QuickAndroid.Styles 0.1 +import AndroidNative 1.0 as AN +import "../theme" + +Page { + + actionBar: ActionBar { + id : actionBar + title: "Notification" + z: 10 + upEnabled: true + onActionButtonClicked: back(); + } + + Button { + id: label + text : "Press to send notification" + anchors.centerIn: parent + onClicked: { + AN.SystemDispatcher.dispatch("Notifier.notify",{ + title: "Quick Android Example", + message: "Hello!" + }); + } + } + +} diff --git a/source-android/androidnative.pri/examples/androidnativeexample/qml.qrc b/source-android/androidnative.pri/examples/androidnativeexample/qml.qrc new file mode 100644 index 0000000..225e836 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/qml.qrc @@ -0,0 +1,31 @@ + + + main.qml + res/drawable-hdpi/icon.png + Components.qml + res/drawable-xxhdpi/ic_menu.png + dialog/DialogDemo.qml + notification/NotificationDemo.qml + theme/AppTheme.qml + theme/qmldir + res/drawable-hdpi/ic_android_black_48dp.png + res/drawable-xxhdpi/ic_android_black_48dp.png + res/drawable-mdpi/ic_android_black_48dp.png + res/drawable-xhdpi/ic_android_black_48dp.png + res/drawable-xxxhdpi/ic_android_black_48dp.png + res/drawable-hdpi/ic_done_black_24dp.png + res/drawable-mdpi/ic_done_black_24dp.png + res/drawable-xhdpi/ic_done_black_24dp.png + res/drawable-xxhdpi/ic_done_black_24dp.png + res/drawable-xxxhdpi/ic_done_black_24dp.png + theme/ActionBarBackground.qml + res/drawable-xxhdpi/ic_keyboard_backspace.png + res/drawable-xxhdpi/ic_arrow_back.png + res/drawable-xxhdpi/ic_image.png + res/drawable-xxhdpi/ic_camera.png + imagePicker/ImagePickerDemo.qml + info/InfoDemo.qml + toast/ToastDemo.qml + statusbar/StatusBarDemo.qml + + diff --git a/source-android/androidnative.pri/examples/androidnativeexample/qpm.json b/source-android/androidnative.pri/examples/androidnativeexample/qpm.json new file mode 100644 index 0000000..9ff04fd --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/qpm.json @@ -0,0 +1,10 @@ +{ + "name": "", + "description": "", + "dependencies": [ + "com.github.benlau.quickandroid@0.1.7" + ], + "license": "NONE", + "pri_filename": "", + "webpage": "" +} \ No newline at end of file diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-hdpi/ic_android_black_48dp.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-hdpi/ic_android_black_48dp.png new file mode 100644 index 0000000..6006b12 Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-hdpi/ic_android_black_48dp.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-hdpi/ic_done_black_24dp.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-hdpi/ic_done_black_24dp.png new file mode 100644 index 0000000..d4c0607 Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-hdpi/ic_done_black_24dp.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-hdpi/icon.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-hdpi/icon.png new file mode 100644 index 0000000..156243d Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-hdpi/icon.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-mdpi/ic_android_black_48dp.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-mdpi/ic_android_black_48dp.png new file mode 100644 index 0000000..41558f2 Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-mdpi/ic_android_black_48dp.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-mdpi/ic_done_black_24dp.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-mdpi/ic_done_black_24dp.png new file mode 100644 index 0000000..5e5e7cf Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-mdpi/ic_done_black_24dp.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xhdpi/ic_android_black_48dp.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xhdpi/ic_android_black_48dp.png new file mode 100644 index 0000000..4f935bf Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xhdpi/ic_android_black_48dp.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xhdpi/ic_done_black_24dp.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xhdpi/ic_done_black_24dp.png new file mode 100644 index 0000000..64a4944 Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xhdpi/ic_done_black_24dp.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_android_black_48dp.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_android_black_48dp.png new file mode 100644 index 0000000..149b4ec Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_android_black_48dp.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_arrow_back.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_arrow_back.png new file mode 100644 index 0000000..1e88d35 Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_arrow_back.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_camera.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_camera.png new file mode 100644 index 0000000..91f103d Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_camera.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_done_black_24dp.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_done_black_24dp.png new file mode 100644 index 0000000..c9c0174 Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_done_black_24dp.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_image.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_image.png new file mode 100644 index 0000000..b32faff Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_image.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_keyboard_backspace.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_keyboard_backspace.png new file mode 100644 index 0000000..a49c20c Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_keyboard_backspace.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_menu.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_menu.png new file mode 100755 index 0000000..ab83be5 Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxhdpi/ic_menu.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxxhdpi/ic_android_black_48dp.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxxhdpi/ic_android_black_48dp.png new file mode 100644 index 0000000..ded531f Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxxhdpi/ic_android_black_48dp.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxxhdpi/ic_done_black_24dp.png b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxxhdpi/ic_done_black_24dp.png new file mode 100644 index 0000000..2f6d638 Binary files /dev/null and b/source-android/androidnative.pri/examples/androidnativeexample/res/drawable-xxxhdpi/ic_done_black_24dp.png differ diff --git a/source-android/androidnative.pri/examples/androidnativeexample/statusbar/StatusBarDemo.qml b/source-android/androidnative.pri/examples/androidnativeexample/statusbar/StatusBarDemo.qml new file mode 100644 index 0000000..0d82d01 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/statusbar/StatusBarDemo.qml @@ -0,0 +1,47 @@ +import QtQuick 2.2 +import QtQuick.Window 2.1 +import QtQuick.Controls 2.1 as QQC2 +import QuickAndroid 0.1 +import QuickAndroid.Styles 0.1 +import AndroidNative 1.0 as AN +import "../theme" + +Page { + + actionBar: ActionBar { + id : actionBar + title: "Status Bar" + z: 10 + upEnabled: true + onActionButtonClicked: back(); + } + + Column { + anchors.centerIn: parent + + QQC2.Switch { + text: "Translucent Status Bar" + checked: false + + onCheckedChanged: { + AN.SystemDispatcher.dispatch("androidnative.Util.setTranslucentStatusBar", {value: checked}); + } + } + + QQC2.Switch { + text: "Status Bar Visible" + checked: true + + onCheckedChanged: { + AN.SystemDispatcher.dispatch("androidnative.Util.setFullScreen", {value: checked}); + } + } + + } + + Component.onCompleted: { + AN.SystemDispatcher.loadClass("androidnative.Util"); + } + + +} diff --git a/source-android/androidnative.pri/examples/androidnativeexample/theme/ActionBarBackground.qml b/source-android/androidnative.pri/examples/androidnativeexample/theme/ActionBarBackground.qml new file mode 100644 index 0000000..1adb0f1 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/theme/ActionBarBackground.qml @@ -0,0 +1,17 @@ +import QtQuick 2.0 +import QuickAndroid 0.1 + +Item { + + MaterialShadow { + asynchronous: true + anchors.fill: parent + depth: 1 + } + + Rectangle { + color: "#cddc39" // Lime 500 + anchors.fill: parent + } +} + diff --git a/source-android/androidnative.pri/examples/androidnativeexample/theme/AppTheme.qml b/source-android/androidnative.pri/examples/androidnativeexample/theme/AppTheme.qml new file mode 100644 index 0000000..9ee92c2 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/theme/AppTheme.qml @@ -0,0 +1,33 @@ +import QtQuick 2.0 +import QuickAndroid 0.1 +import QuickAndroid.Styles 0.1 +pragma Singleton + +Theme { + mediumText.textSize: 18 * A.dp + smallText.textSize : 14 * A.dp + + colorPrimary: "#cddc39" // Lime 500 + textColorPrimary: Constants.black87 + windowBackground: "#eeeeee"; + + // The default icon of ActionBar is a "back" image + actionBar.iconSource: A.drawable("ic_arrow_back",Constants.black87) + + // Background with shadow + actionBar.background: ActionBarBackground { + } + + // actionBar.title.textSize is not allowed in QML. You should declare your own TextMaterial and assign directly. + // or modify text , smallText , mediumText and largetText + actionBar.title : customTextMaterial1; + actionBar.iconSourceSize: Qt.size(24 * A.dp , 24 * A.dp) + + // Custom Style object. + TextMaterial { + id : customTextMaterial1 + textSize: 18 * A.dp + textColor : Constants.black87 + } +} + diff --git a/source-android/androidnative.pri/examples/androidnativeexample/theme/qmldir b/source-android/androidnative.pri/examples/androidnativeexample/theme/qmldir new file mode 100644 index 0000000..5a1f2f4 --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/theme/qmldir @@ -0,0 +1,2 @@ +module theme +singleton AppTheme 0.1 AppTheme.qml diff --git a/source-android/androidnative.pri/examples/androidnativeexample/toast/ToastDemo.qml b/source-android/androidnative.pri/examples/androidnativeexample/toast/ToastDemo.qml new file mode 100644 index 0000000..f5e23bd --- /dev/null +++ b/source-android/androidnative.pri/examples/androidnativeexample/toast/ToastDemo.qml @@ -0,0 +1,33 @@ +import QtQuick 2.2 +import QtQuick.Window 2.1 +import QuickAndroid 0.1 +import QuickAndroid.Styles 0.1 +import AndroidNative 1.0 as AN +import "../theme" + +Page { + + actionBar: ActionBar { + id : actionBar + title: "Toast" + z: 10 + upEnabled: true + onActionButtonClicked: back(); + } + + AN.Toast { + id: toast + text: "Toast" + longDuration: true + } + + Button { + id: label + text : "Press to show toast" + anchors.centerIn: parent + onClicked: { + toast.show(); + } + } + +} diff --git a/source-android/androidnative.pri/java/src/androidnative/AndroidNativeActivity.java b/source-android/androidnative.pri/java/src/androidnative/AndroidNativeActivity.java new file mode 100644 index 0000000..c63c3b8 --- /dev/null +++ b/source-android/androidnative.pri/java/src/androidnative/AndroidNativeActivity.java @@ -0,0 +1,23 @@ +package androidnative; +import android.content.Intent; + +/** An alternative Activity class for Qt applicaiton. + + Remarks: It is recommended but not a must to use this class as the main activity. + */ + +public class AndroidNativeActivity extends org.qtproject.qt5.android.bindings.QtActivity { + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + SystemDispatcher.onActivityResult(requestCode,resultCode,data); + } + + protected void onResume() { + super.onResume(); + SystemDispatcher.onActivityResume(); + } + +} + diff --git a/source-android/androidnative.pri/java/src/androidnative/ImagePicker.java b/source-android/androidnative.pri/java/src/androidnative/ImagePicker.java new file mode 100644 index 0000000..5d515f8 --- /dev/null +++ b/source-android/androidnative.pri/java/src/androidnative/ImagePicker.java @@ -0,0 +1,236 @@ +package androidnative; +import org.qtproject.qt5.android.QtNative; +import android.content.Intent; +import android.util.Log; +import android.app.Activity; +import java.util.Map; +import android.net.Uri; +import java.util.HashMap; +import android.database.Cursor; +import android.provider.MediaStore; + +import java.text.SimpleDateFormat; +import java.io.File; +import java.util.Date; +import android.os.Environment; +import android.content.ClipData; +import java.util.List; +import java.util.ArrayList; + +public class ImagePicker { + + // Random + public static final int PICK_IMAGE_ACTION = 0x245285a3; + public static final int TAKE_PHOTO_ACTION = 0x29fe8748; + + public static final String PICK_IMAGE_MESSAGE = "androidnative.ImagePicker.pickImage"; + public static final String TAKE_PHOTO_MESSAGE = "androidnative.ImagePicker.takePhoto"; + public static final String CHOSEN_MESSAGE = "androidnative.ImagePicker.chosen"; + + private static final String TAG = "androidnative.ImagePicker"; + + private static Uri mPhotoUri; + private static Boolean broadcast = false; + + static { + SystemDispatcher.addListener(new SystemDispatcher.Listener() { + public void onDispatched(String type , Map message) { + if (type.equals(PICK_IMAGE_MESSAGE)) { + pickImage(message); + } else if (type.equals(TAKE_PHOTO_MESSAGE)) { + takePhoto(message); + } else if (type.equals(SystemDispatcher.ACTIVITY_RESULT_MESSAGE)) { + onActivityResult(message); + } + } + }); + } + + static void pickImage(Map message) { + Boolean multiple = false; + Activity activity = org.qtproject.qt5.android.QtNative.activity(); + + Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); + + if (message.containsKey("multiple")) { + multiple = (Boolean) message.get("multiple"); + } + + if (multiple) { + intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); + } + + // >= API 18 + activity.startActivityForResult(intent, PICK_IMAGE_ACTION); + } + + static void takePhoto(Map message) { + if (message.containsKey("broadcast")) { + broadcast = (Boolean) message.get("broadcast"); + } + + String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss").format(new Date()); + File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); + if(!storageDir.exists() && !storageDir.mkdir()) + return; + + File image = new File(storageDir.getAbsolutePath() + "/" + timeStamp + ".jpg"); + mPhotoUri = Uri.fromFile(image); + + Log.d(TAG,"takePhoto : " + mPhotoUri); + + Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); + intent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); + intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); + intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); + + Activity activity = org.qtproject.qt5.android.QtNative.activity(); + activity.startActivityForResult(intent,TAKE_PHOTO_ACTION); + } + + static private void onActivityResult(Map message) { + int resultCode = (Integer) message.get("resultCode"); + if (resultCode != Activity.RESULT_OK) + return; + int requestCode = (Integer) message.get("requestCode"); + Intent data = (Intent) message.get("data"); + + if (requestCode == PICK_IMAGE_ACTION) { + importImage(data); + } else if (requestCode == TAKE_PHOTO_ACTION) { + // Android 4.x. data will be null. + // Android 6.x. data is not null + importImageFromFileUri(mPhotoUri); + if (broadcast) + broadcastToMediaScanner(mPhotoUri); + } + } + + static private void importImage(Intent data) { + Uri uri = data.getData(); + + Log.d(TAG,"importImage: uri:" + uri); + Log.d(TAG,"importImage: type: " + data.getType()); + + if (data.getClipData() != null) { + importImageFromClipData(data); + } else if (uri != null ) { + if (uri.getScheme().equals("file")) { + importImageFromFileUri(uri); + } else { + importImageFromContentUri(uri); + } + } + + } + + static private void importImageFromFileUri(Uri uri) { + ArrayList list = new ArrayList(1); + list.add(uri); + importImageFromFileUri(list); + } + + static private void importImageFromFileUri(List uris) { + Map reply = new HashMap(); + ArrayList list = new ArrayList(uris.size()); + for (int i = 0 ; i < uris.size() ; i++) { + list.add(uris.get(i).toString()); + } + reply.put("imageUrls",list); + SystemDispatcher.dispatch(CHOSEN_MESSAGE,reply); + } + + + static private void importImageFromContentUri(Uri uri) { + Activity activity = org.qtproject.qt5.android.QtNative.activity(); + + String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.ImageColumns.ORIENTATION }; + + Cursor cursor = activity.getContentResolver().query(uri, columns, null, null, null); + if (cursor == null) { + Log.d(TAG,"importImageFromContentUri: Query failed"); + return; + } + + cursor.moveToFirst(); + ArrayList uris = new ArrayList(cursor.getCount()); + + for (int i = 0 ; i < cursor.getCount(); i++) { + int columnIndex; + columnIndex = cursor.getColumnIndex(columns[0]); + String path = cursor.getString(columnIndex); + + /* + columnIndex = cursor.getColumnIndex(columns[1]); + int orientation = cursor.getInt(columnIndex); + */ + + if (path == null) { + Log.d(TAG,"importImageFromContentUri: The path of image is null. The image may not on the storage."); + continue; + } + + Uri fileUri = Uri.fromParts("file",path,""); + uris.add(fileUri); + + Log.d(TAG,"importImageFromContentUri: " + fileUri.toString()); + } + + importImageFromFileUri(uris); + cursor.close(); + + + + } + + private static void importImageFromClipData(Intent data) { + ClipData clipData = data.getClipData(); + + Log.d(TAG,"importFromClipData"); + + if (clipData.getItemCount() == 0) + return; + + ArrayList uris = new ArrayList(clipData.getItemCount()); + + for (int i = 0 ; i < clipData.getItemCount() ; i++ ){ + Uri uri = clipData.getItemAt(i).getUri(); + uris.add(resolveUri(uri)); + } + importImageFromFileUri(uris); + } + + static private Uri resolveUri(Uri uri) { + Activity activity = org.qtproject.qt5.android.QtNative.activity(); + + String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.ImageColumns.ORIENTATION}; + + Cursor cursor = activity.getContentResolver().query(uri, columns, null, null, null); + if (cursor == null) { + Log.d(TAG,"Query failed"); + return Uri.parse(""); + } + + cursor.moveToFirst(); + int columnIndex; + + columnIndex = cursor.getColumnIndex(columns[0]); + String path = cursor.getString(columnIndex); + +// columnIndex = cursor.getColumnIndex(columns[1]); +// int orientation = cursor.getInt(columnIndex); + cursor.close(); + return Uri.fromParts("file",path,""); + } + + private static void broadcastToMediaScanner(Uri uri) { + Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); + mediaScanIntent.setData(uri); + + Activity activity = org.qtproject.qt5.android.QtNative.activity(); + activity.sendBroadcast(mediaScanIntent); + } + +} + diff --git a/source-android/androidnative.pri/java/src/androidnative/MediaScanner.java b/source-android/androidnative.pri/java/src/androidnative/MediaScanner.java new file mode 100644 index 0000000..93cfd1b --- /dev/null +++ b/source-android/androidnative.pri/java/src/androidnative/MediaScanner.java @@ -0,0 +1,35 @@ +package androidnative; + +import android.app.Activity; +import org.qtproject.qt5.android.QtNative; +import java.util.Map; +import android.media.MediaScannerConnection; + +/** + * Created by benlau on 19/2/2017. + */ + +public class MediaScanner { + + + public static final String SCAN_FILE = "androidnative.MediaScanner.scanFile"; + + static { + SystemDispatcher.addListener(new SystemDispatcher.Listener() { + public void onDispatched(String type, Map message) { + if (type.equals(SCAN_FILE)) { + scanFile(message); + } + } + }); + } + + static void scanFile(Map message) { + Activity activity = org.qtproject.qt5.android.QtNative.activity(); + + String path = (String) message.get("path"); + + MediaScannerConnection.scanFile(activity, new String[] {path}, null, null); + } + +} \ No newline at end of file diff --git a/source-android/androidnative.pri/java/src/androidnative/SystemDispatcher.java b/source-android/androidnative.pri/java/src/androidnative/SystemDispatcher.java new file mode 100644 index 0000000..b35dff3 --- /dev/null +++ b/source-android/androidnative.pri/java/src/androidnative/SystemDispatcher.java @@ -0,0 +1,218 @@ +// Author: Ben Lau (https://github.com/benlau) +package androidnative; +import android.app.Activity; +import org.qtproject.qt5.android.QtNative; +import java.lang.String; +import java.util.Map; +import java.util.HashMap; +import java.util.List; +import java.util.Set; +import java.util.ArrayList; +import java.util.Queue; +import java.util.LinkedList; +import java.lang.ClassLoader; +import java.lang.reflect.Method; +import java.lang.Thread; +import android.util.Log; +import android.os.Handler; +import android.os.Looper; +import android.content.Intent; +import java.util.concurrent.Semaphore; +import java.io.StringWriter; +import java.io.PrintWriter; + +public class SystemDispatcher { + + public interface Listener { + /** Every messages posted on SystemMessenger will trigger this function. + + @return true if the message is handled. Otherwise, it should be false. + */ + public void onDispatched(String type , Map message); + } + + /** + @threadsafe + @remarks: The function may not be running from the UI thread. It is listener's duty to handle multiple threading issue. + */ + + public static void dispatch(String name) { + dispatch(name,null); + } + + /** Dispatch a message. + @threadsafe + @remarks: The function may not be running from the UI thread. It is listener's duty to handle multiple threading issue. + */ + public static void dispatch(String type,Map message) { + try { + + Payload payload; + + mutex.acquire(); + + if (dispatching) { + payload = new Payload(); + payload.type = type; + payload.message = message; + queue.add(payload); + mutex.release(); + return; + } + + dispatching = true; + mutex.release(); + + emit(type,message); // Emit + + mutex.acquire(); // Process queued message + + while (queue.size() > 0 ) { + payload = queue.poll(); + mutex.release(); + + emit(payload.type,payload.message); + + mutex.acquire(); + } + dispatching = false; + mutex.release(); + + } catch (Exception e) { + Log.e(TAG,"exception",e); + } + } + + public static void addListener(Listener listener ) { + try { + mutex.acquire(); + listeners.add(listener); + mutex.release(); + } catch (Exception e) { + Log.e(TAG,"exception",e); + } + + } + + public static void removeListener(Listener listener ) { + try { + mutex.acquire(); + listeners.remove(listener); + mutex.release(); + } catch (Exception e) { + Log.e(TAG,"exception",e); + } + } + + public static String ACTIVITY_RESUME_MESSAGE = "androidnative.Activity.onResume"; + + public static String ACTIVITY_RESULT_MESSAGE = "androidnative.Activity.onActivityResult"; + + public static String SYSTEM_DISPATCHER_LOAD_CLASS_MESSAGE = "androidnative.SystemDispatcher.loadClass"; + + /** A helper function to dispatch a massage when onResume is invoked in the Activity class + */ + + public static void onActivityResume() { + dispatch(ACTIVITY_RESUME_MESSAGE); + } + + /** A helper function to dispatch a message based on the input argument fron Activity.onActivityResult + */ + public static void onActivityResult (int requestCode, int resultCode, Intent data) { + Map message = new HashMap(); + + message.put("requestCode",requestCode); + message.put("resultCode",resultCode); + message.put("data",data); + + dispatch(ACTIVITY_RESULT_MESSAGE,message); + } + + private static class Payload { + public String type; + public Map message; + } + + private static String TAG = "AndroidNative"; + + private static final Semaphore mutex = new Semaphore(1); + + private static Queue queue = new LinkedList(); + + private static List listeners = new ArrayList(); + + private static boolean dispatching = false; + + private static native void jniEmit(String name,Map message); + + /** Emit onDispatched signal to registered listenter + */ + private static void emit(String name,Map message) { + for (int i = 0 ; i < listeners.size() ; i++ ) { + Listener listener = listeners.get(i); + try { + listener.onDispatched(name,message); + } catch (Exception e) { + Log.d(TAG, Log.getStackTraceString(e)); + } + } + + jniEmit(name,message); + } + + private static void printMap(Map data) { + if (data == null) + return; + try { + for (Map.Entry entry : (Set) data.entrySet()) { + String key = (String) entry.getKey(); + Object value = entry.getValue(); + if (value == null) + continue; + + if (value instanceof String) { + String stringValue = (String) value; + Log.d(TAG,String.format("%s : %s",key,stringValue)); + } else if (value instanceof Integer) { + int intValue = (Integer) value; + Log.d(TAG,String.format("%s : %d",key,intValue)); + } else if (value instanceof Boolean) { + Boolean booleanValue = (Boolean) value; + Log.d(TAG,String.format("%s : %b",key,booleanValue)); + } else { + Log.d(TAG,String.format("%s : Non-supported data type[%s] is passed",key,value.getClass().getName())); + } + } + } catch (Exception e) { + Log.d(TAG,e.getMessage()); + } + + } + + public static void loadClass(String className) { + try { + ClassLoader classLoader = SystemDispatcher.class.getClassLoader(); + Class aClass = Class.forName(className,true,classLoader); +// Log.d(TAG,"Class Loaded: " + className); + } catch (ClassNotFoundException e) { + Log.e(TAG,"Failed to load class: " + className); + e.printStackTrace(); + } + } + + public static void init() { + SystemDispatcher.addListener(new SystemDispatcher.Listener() { + public void onDispatched(String type , Map message) { +// Log.d(TAG,String.format("%s %b",type ,type.equals(SYSTEM_DISPATCHER_LOAD_CLASS_MESSAGE))); + + if (type.equals(SYSTEM_DISPATCHER_LOAD_CLASS_MESSAGE)) { + String className = (String) message.get("className"); + loadClass(className); + } + } + }); + + } + +} diff --git a/source-android/androidnative.pri/java/src/androidnative/Toast.java b/source-android/androidnative.pri/java/src/androidnative/Toast.java new file mode 100644 index 0000000..a18a45e --- /dev/null +++ b/source-android/androidnative.pri/java/src/androidnative/Toast.java @@ -0,0 +1,41 @@ +package androidnative; + +import android.app.Activity; +import android.util.Log; +import java.util.Map; + +import org.qtproject.qt5.android.QtNative; + +public class Toast { + public static final String TOAST_MESSAGE = "androidnative.Toast.showToast"; + + private static final String TAG = "androidnative.Toast"; + + static { + SystemDispatcher.addListener(new SystemDispatcher.Listener() { + public void onDispatched(String type, Map message) { + if (type.equals(TOAST_MESSAGE)) { + showToast(message); + } + } + }); + } + + static void showToast(Map message) { + if (!message.containsKey("text")) { + Log.d(TAG, "showToast: no text"); + return; + } + + int duration = android.widget.Toast.LENGTH_SHORT; + if (message.containsKey("longLength")) { + Boolean isLong = (Boolean)message.get("longLength"); + if (isLong != null && isLong == true) + duration = android.widget.Toast.LENGTH_LONG; + } + + Activity activity = QtNative.activity(); + activity.runOnUiThread(new ToastRunnable(activity, (String)message.get("text"), duration)); + } +} + diff --git a/source-android/androidnative.pri/java/src/androidnative/ToastRunnable.java b/source-android/androidnative.pri/java/src/androidnative/ToastRunnable.java new file mode 100644 index 0000000..97c4537 --- /dev/null +++ b/source-android/androidnative.pri/java/src/androidnative/ToastRunnable.java @@ -0,0 +1,22 @@ +package androidnative; + +import android.app.Activity; +import android.widget.Toast; + +public class ToastRunnable implements Runnable { + private Activity activity; + private String text; + private int duration; + + public ToastRunnable(Activity activity, String text, int duration) { + this.activity = activity; + this.text = text; + this.duration = duration; + } + + @Override + public void run() { + Toast.makeText(activity, text, duration).show(); + } +} + diff --git a/source-android/androidnative.pri/java/src/androidnative/Util.java b/source-android/androidnative.pri/java/src/androidnative/Util.java new file mode 100644 index 0000000..d016af5 --- /dev/null +++ b/source-android/androidnative.pri/java/src/androidnative/Util.java @@ -0,0 +1,87 @@ +package androidnative; + +import android.app.Activity; +import android.os.Build; +import android.util.Log; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; + +import org.qtproject.qt5.android.QtNative; + +import java.util.Map; + +public class Util { + + private static final String TAG = "androidnative.Util"; + + public static final String SET_TRANSLUCENT_STATUS_BAR = "androidnative.Util.setTranslucentStatusBar"; + public static final String SET_FULL_SCREEN = "androidnative.Util.setFullScreen"; + + + static { + SystemDispatcher.addListener(new SystemDispatcher.Listener() { + public void onDispatched(String type, Map message) { + if (type.equals(SET_TRANSLUCENT_STATUS_BAR)) { + setTranslucentStatusBar(message); + } else if (type.equals(SET_FULL_SCREEN)) { + setFullScreen(message); + } + } + }); + } + + static void setTranslucentStatusBar(Map message) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { + return; + } + + final Boolean value = (Boolean) message.get("value"); + final Activity activity = QtNative.activity(); + + Runnable runnable = new Runnable () { + public void run() { + Window w = activity.getWindow(); // in Activity's onCreate() for instance + + if (value) { +// w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); + w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + } else { +// w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); + w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + } + } + }; + + activity.runOnUiThread(runnable); + + } + + static void setFullScreen(Map message) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { + return; + } + + final Boolean value = (Boolean) message.get("value"); + final Activity activity = QtNative.activity(); + + Runnable runnable = new Runnable () { + public void run() { + Window w = activity.getWindow(); // in Activity's onCreate() for instance + View decorView = w.getDecorView(); + + int config = decorView.getSystemUiVisibility(); + + if (value) { + config &= ~View.SYSTEM_UI_FLAG_FULLSCREEN; + } else { + config |= View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; + } + decorView.setSystemUiVisibility(config); + } + }; + + activity.runOnUiThread(runnable); + + } +} diff --git a/source-android/androidnative.pri/java/src/androidnative/VideoPicker.java b/source-android/androidnative.pri/java/src/androidnative/VideoPicker.java new file mode 100644 index 0000000..c935e43 --- /dev/null +++ b/source-android/androidnative.pri/java/src/androidnative/VideoPicker.java @@ -0,0 +1,344 @@ +package androidnative; +import org.qtproject.qt5.android.QtNative; +import android.content.Intent; +import android.content.Context; +import android.util.Log; +import android.app.Activity; +import java.util.Map; +import android.net.Uri; +import java.util.HashMap; +import android.database.Cursor; +import android.content.ContentResolver ; +import android.content.ContentValues ; +import android.provider.MediaStore; +import android.media.ThumbnailUtils ; + +import java.text.SimpleDateFormat; +import java.io.File; +import java.io.OutputStream; +import java.io.FileNotFoundException ; +import java.io.IOException ; +import java.util.Date; +import android.os.Environment; +import android.content.ClipData; +import java.util.List; +import java.util.ArrayList; +import android.graphics.Bitmap ; + + + + + +public class VideoPicker { + + // Random , generated using : $ openssl rand -hex 3 + public static final int PICK_VIDEO_ACTION = 0x7c43f0; + public static final int TAKE_VIDEO_ACTION = 0x4df0bc; + + + public static final String PICK_VIDEO_MESSAGE = "androidnative.VideoPicker.pickVideo"; + public static final String TAKE_VIDEO_MESSAGE = "androidnative.VideoPicker.takeVideo"; + public static final String CHOSEN_MESSAGE = "androidnative.VideoPicker.chosen"; + + private static final String TAG = "androidnative.VideoPicker"; + + private static Uri mVideoUri; + private static Boolean broadcast = false; + + static { + SystemDispatcher.addListener(new SystemDispatcher.Listener() { + public void onDispatched(String type , Map message) { + Log.d(TAG,"onDispatched called with type :" + type ); + if (type.equals(PICK_VIDEO_MESSAGE)) { + Log.d(TAG,"type is PICK_VIDEO_MESSAGE" ); + pickVideo(message); + } else if (type.equals(TAKE_VIDEO_MESSAGE)) { + Log.d(TAG,"type is TAKE_VIDEO_MESSAGE" ); + takeVideo(message); + } else if (type.equals(SystemDispatcher.ACTIVITY_RESULT_MESSAGE)) { + Log.d(TAG,"type is ACTIVITY_RESULT_MESSAGE" ); + onActivityResult(message); + } + } + }); + } + + static void pickVideo(Map message) { + Boolean multiple = false; + Activity activity = org.qtproject.qt5.android.QtNative.activity(); + + Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI); + intent.setType("video/*"); + + if (message.containsKey("multiple")) { + multiple = (Boolean) message.get("multiple"); + } + + if (multiple) { + intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); + } + + // >= API 18 + activity.startActivityForResult(intent, PICK_VIDEO_ACTION); + } + + static void takeVideo(Map message) { + if (message.containsKey("broadcast")) { + broadcast = (Boolean) message.get("broadcast"); + } + + Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); + Activity activity = org.qtproject.qt5.android.QtNative.activity(); + if (takeVideoIntent.resolveActivity(activity.getPackageManager()) != null) { + activity.startActivityForResult(takeVideoIntent, TAKE_VIDEO_ACTION ); + } + } + + static private void onActivityResult(Map message) { + + int resultCode = (Integer) message.get("resultCode"); + if (resultCode != Activity.RESULT_OK) + return; + int requestCode = (Integer) message.get("requestCode"); + Intent data = (Intent) message.get("data"); + + if (requestCode == PICK_VIDEO_ACTION) { + importVideo(data); + } else if (requestCode == TAKE_VIDEO_ACTION) { + // Android 4.x. data will be null. + // Android 6.x. data is not null + + Log.d(TAG,"request code is TAKE_VIDEO_ACTION:" + TAKE_VIDEO_ACTION ); + mVideoUri = data.getData(); + Log.d(TAG, "after TAKE_VIDEO_ACTION mVideoUri is: " + mVideoUri ); + if (mVideoUri != null ) { + importVideoFromContentUri(mVideoUri); + } + + if (broadcast) + broadcastToMediaScanner(mVideoUri); + } + } + + static private void importVideo(Intent data) { + Uri uri = data.getData(); + + Log.d(TAG,"importVideo: uri:" + uri); + Log.d(TAG,"importVideo: type: " + data.getType()); + + if (data.getClipData() != null) { + importVideoFromClipData(data); + } else if (uri != null ) { + if (uri.getScheme().equals("file")) { + importVideoFromFileUri(uri); + } else { + importVideoFromContentUri(uri); + } + } + + } + + static private void importVideoFromFileUri(Uri uri) { + ArrayList list = new ArrayList(1); + list.add(uri); + importVideoFromFileUri(list); + } + + static private void importVideoFromFileUri(List uris) { + Map reply = new HashMap(); + ArrayList list = new ArrayList(uris.size()); + ArrayList thumbList = new ArrayList(uris.size()); + + Activity activity = org.qtproject.qt5.android.QtNative.activity(); + for (int i = 0 ; i < uris.size() ; i++) { + + Uri uri = Uri.parse( Uri.decode(uris.get(i).toString())); + String thumbPath = getVideoThumbnail(activity , uri.getPath() ); + Uri thumbUri = Uri.fromParts("file", thumbPath ,""); + thumbList.add(thumbUri.toString()); + list.add(uris.get(i).toString()); + } + reply.put("videoUrls",list); + reply.put("videoThumbUrls",thumbList); + Log.d(TAG , "dispatching to systemdispatcher with CHOSEN_MESSAGE" ); + SystemDispatcher.dispatch(CHOSEN_MESSAGE,reply); + } + + + static private void importVideoFromContentUri(Uri uri) { + Activity activity = org.qtproject.qt5.android.QtNative.activity(); + + String[] columns = { MediaStore.Video.Media.DATA }; + + Cursor cursor = activity.getContentResolver().query(uri, columns, null, null, null); + if (cursor == null) { + Log.d(TAG,"importVideoFromContentUri: Query failed"); + return; + } + + cursor.moveToFirst(); + ArrayList uris = new ArrayList(cursor.getCount()); + + for (int i = 0 ; i < cursor.getCount(); i++) { + int columnIndex; + columnIndex = cursor.getColumnIndex(columns[0]); + String path = cursor.getString(columnIndex); + + if (path == null) { + Log.d(TAG,"importVideoFromContentUri: The path of video is null. The video may not on the storage."); + continue; + } + + Uri fileUri = Uri.fromParts("file",path,""); + uris.add(fileUri); + + Log.d(TAG,"importVideoFromContentUri: " + fileUri.toString()); + } + + importVideoFromFileUri(uris); + cursor.close(); + + } + + public static String getVideoThumbnail(Context context, String filePath ) { + + Log.d(TAG , "getVideoThumbnail called for filePath:" + filePath); + // first get the VideoId from the path + + String[] columns = { + MediaStore.Video.Media._ID + }; + + ContentResolver cr = context.getContentResolver(); + + Cursor cursor = cr.query( + android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI , columns, + MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null); + cursor.moveToFirst(); + + if (cursor == null) { + Log.e(TAG,"query for videoId failed"); + return null; + } + cursor.moveToFirst(); + long videoId = cursor.getLong(0); + + Log.d(TAG , "getVideoThumbnail videoId: " + videoId); + + // use videoId to get the thumbnail path + try { + + String[] projection = { + MediaStore.Video.Thumbnails.DATA, + }; + cursor = cr.query( + MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, + projection, + MediaStore.Video.Thumbnails.VIDEO_ID + "=?", + new String[] { String.valueOf(videoId) }, + null); + if (cursor.getCount() > 0 ) { + cursor.moveToFirst(); + return cursor.getString(0); + } + + Log.w(TAG, "Sorry no thumbnail found with video id: " + videoId); + Log.d(TAG, "Generating new thumbnail." ); + Bitmap bMap = ThumbnailUtils.createVideoThumbnail( filePath , MediaStore.Video.Thumbnails.MICRO_KIND); + + if (bMap != null) { + Log.d(TAG, "storing new thumbnail." ); + storeThumbnail(cr , bMap , videoId , MediaStore.Video.Thumbnails.MICRO_KIND); + } + + // Query again after storing the Thumbnail in MediaStrore.Video.Thumbnails + Log.d(TAG, "Querying again for thumbnail" ); + cursor = cr.query( + MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, + projection, + MediaStore.Video.Thumbnails.VIDEO_ID + "=?", + new String[] { String.valueOf(videoId) }, + null); + + if (cursor.getCount() > 0 ) { + Log.d(TAG, "Got thumbnail in second query." ); + cursor.moveToFirst(); + return cursor.getString(0); + } + + } catch (Exception e) { + Log.e(TAG, Log.getStackTraceString(e)); + } + return null; + } + + private static void importVideoFromClipData(Intent data) { + ClipData clipData = data.getClipData(); + + Log.d(TAG,"Video importFromClipData"); + + if (clipData.getItemCount() == 0) + return; + + ArrayList uris = new ArrayList(clipData.getItemCount()); + + for (int i = 0 ; i < clipData.getItemCount() ; i++ ){ + Uri uri = clipData.getItemAt(i).getUri(); + uris.add(resolveUri(uri)); + } + importVideoFromFileUri(uris); + } + + + + static private Uri resolveUri(Uri uri) { + Activity activity = org.qtproject.qt5.android.QtNative.activity(); + + String[] columns = { MediaStore.Video.Media.DATA }; + + Cursor cursor = activity.getContentResolver().query(uri, columns, null, null, null); + if (cursor == null) { + Log.d(TAG,"Query failed"); + return Uri.parse(""); + } + + cursor.moveToFirst(); + int columnIndex; + + columnIndex = cursor.getColumnIndex(columns[0]); + String path = cursor.getString(columnIndex); + + cursor.close(); + return Uri.fromParts("file",path,""); + } + + private static void broadcastToMediaScanner(Uri uri) { + Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); + mediaScanIntent.setData(uri); + Activity activity = org.qtproject.qt5.android.QtNative.activity(); + activity.sendBroadcast(mediaScanIntent); + } + + private static void storeThumbnail(ContentResolver cr, Bitmap thumb, long id, int kind) { + + ContentValues values = new ContentValues(4); + values.put(MediaStore.Video.Thumbnails.KIND,kind); + values.put(MediaStore.Video.Thumbnails.VIDEO_ID,(int)id ); + values.put(MediaStore.Video.Thumbnails.HEIGHT,thumb.getHeight()); + values.put(MediaStore.Video.Thumbnails.WIDTH,thumb.getWidth()); + + Uri url = cr.insert(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI, values); + + try { + OutputStream thumbOut = cr.openOutputStream(url); + thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut); + thumbOut.close(); + } catch (FileNotFoundException ex) { + Log.e("IMAGE_COMPRESSION_ERROR", "File not found"); + ex.printStackTrace(); + } catch (IOException ex) { + Log.e("IMAGE_COMPRESSION_ERROR", "IO Exception"); + ex.printStackTrace(); + } + } +} diff --git a/source-android/androidnative.pri/qml/AndroidNative/ImagePicker.qml b/source-android/androidnative.pri/qml/AndroidNative/ImagePicker.qml new file mode 100644 index 0000000..ac8290e --- /dev/null +++ b/source-android/androidnative.pri/qml/AndroidNative/ImagePicker.qml @@ -0,0 +1,53 @@ +import QtQuick 2.0 +import AndroidNative 1.0 + +Item { + + /// Set it to true if multiple images should be picked. + property bool multiple: false + + /// If it is true, it will broadcast the taked photo to other application (e.g Let it show in Google Photos) + property bool broadcast: true + + /// The URL of the image chosen. If multiple images are picked, it will be equal to the first image. + property string imageUrl: "" + + /// A list of images chosen + property var imageUrls: [] + + /// It is emitted whatever photo(s) are picked/taken. + signal ready(); + + function pickImage() { + SystemDispatcher.dispatch(m_PICK_IMAGE_MESSAGE,{ multiple: multiple}); + } + + function takePhoto() { + SystemDispatcher.dispatch(m_TAKE_PHOTO_MESSAGE,{ + broadcast: broadcast + }) + } + + property string m_PICK_IMAGE_MESSAGE: "androidnative.ImagePicker.pickImage"; + + property string m_TAKE_PHOTO_MESSAGE: "androidnative.ImagePicker.takePhoto"; + + property string m_CHOSEN_MESSAGE: "androidnative.ImagePicker.chosen"; + + + Connections { + target: SystemDispatcher + onDispatched: { + if (type === m_CHOSEN_MESSAGE) { + imageUrls = message.imageUrls; + imageUrl = imageUrls[0]; + ready(); + } + } + } + + Component.onCompleted: { + SystemDispatcher.loadClass("androidnative.ImagePicker"); + } +} + diff --git a/source-android/androidnative.pri/qml/AndroidNative/Toast.qml b/source-android/androidnative.pri/qml/AndroidNative/Toast.qml new file mode 100644 index 0000000..a51035f --- /dev/null +++ b/source-android/androidnative.pri/qml/AndroidNative/Toast.qml @@ -0,0 +1,25 @@ +import QtQuick 2.0 +import AndroidNative 1.0 + +Item { + /// The message that will be displayed when show() is called + property string text: '' + + /// If set to true, the toast duration will be long + property bool longDuration: false + + readonly property string m_TOAST_MESSAGE: "androidnative.Toast.showToast" + + /// Displays the Toast with the current set text and duration + function show() { + SystemDispatcher.dispatch(m_TOAST_MESSAGE, { + text: text, + longLength: longDuration + }); + } + + Component.onCompleted: { + SystemDispatcher.loadClass("androidnative.Toast"); + } +} + diff --git a/source-android/androidnative.pri/qml/AndroidNative/VideoPicker.qml b/source-android/androidnative.pri/qml/AndroidNative/VideoPicker.qml new file mode 100644 index 0000000..0931c00 --- /dev/null +++ b/source-android/androidnative.pri/qml/AndroidNative/VideoPicker.qml @@ -0,0 +1,62 @@ +import QtQuick 2.0 +import AndroidNative 1.0 + +Item { + + /// Set it to true if multiple videos should be picked. + property bool multiple: false + + /// If it is true, it will broadcast the taked photo to other application (e.g Let it show in Google Photos) + property bool broadcast: true + + /// The URL of the videos chosen. If multiple videos are picked, it will be equal to the first videos. + property string videoUrl: "" + + /// The URL of the thumbnail of video chosen. If multiple videos are picked, + // it will be equal to the thumbnail of first video. + property string thumbUrl: "" + + /// A list of videos chosen + property var videoUrls: [] + + /// A list of thumbnails of videos chosen + property var thumbUrls: [] + + /// It is emitted whatever photo(s) are picked/taken. + signal ready(); + + function pickVideo() { + SystemDispatcher.dispatch(m_PICK_VIDEO_MESSAGE,{ multiple: multiple }); + } + + function takeVideo() { + SystemDispatcher.dispatch(m_TAKE_VIDEO_MESSAGE,{ broadcast: broadcast }); + } + + property string m_PICK_VIDEO_MESSAGE: "androidnative.VideoPicker.pickVideo"; + + property string m_TAKE_VIDEO_MESSAGE: "androidnative.VideoPicker.takeVideo"; + + property string m_CHOSEN_MESSAGE: "androidnative.VideoPicker.chosen"; + + + Connections { + target: SystemDispatcher + onDispatched: { + if (type === m_CHOSEN_MESSAGE) { + videoUrls = message.videoUrls; + videoUrl = videoUrls[0]; + + thumbUrls = message.videoThumbUrls; + thumbUrl = thumbUrls[0]; + + ready(); + } + } + } + + Component.onCompleted: { + SystemDispatcher.loadClass("androidnative.VideoPicker"); + } +} + diff --git a/source-android/androidnative.pri/qml/AndroidNative/qmldir b/source-android/androidnative.pri/qml/AndroidNative/qmldir new file mode 100644 index 0000000..84d120c --- /dev/null +++ b/source-android/androidnative.pri/qml/AndroidNative/qmldir @@ -0,0 +1,3 @@ +ImagePicker 1.0 ImagePicker.qml +VideoPicker 1.0 VideoPicker.qml +Toast 1.0 Toast.qml diff --git a/source-android/androidnative.pri/qml/androidnative.qrc b/source-android/androidnative.pri/qml/androidnative.qrc new file mode 100644 index 0000000..20798ff --- /dev/null +++ b/source-android/androidnative.pri/qml/androidnative.qrc @@ -0,0 +1,8 @@ + + + AndroidNative/qmldir + AndroidNative/ImagePicker.qml + AndroidNative/Toast.qml + AndroidNative/VideoPicker.qml + + diff --git a/source-android/androidnative.pri/qpm.json b/source-android/androidnative.pri/qpm.json new file mode 100644 index 0000000..27d63dd --- /dev/null +++ b/source-android/androidnative.pri/qpm.json @@ -0,0 +1,22 @@ +{ + "name": "android.native.pri", + "description": "Calling Android functions from Qt without JNI", + "author": { + "name": "Ben Lau", + "email": "xbenlau@gmail.com" + }, + "repository": { + "type": "GITHUB", + "url": "https://github.com/benlau/androidnative.pri" + }, + "version": { + "label": "0.0.5", + "revision": "1", + "fingerprint": "" + }, + "dependencies": [ + ], + "license": "APACHE_2_0", + "pri_filename": "androidnative.pri", + "webpage": "" +} diff --git a/source-android/androidnative.pri/tests/instrument/activity/activity.pro b/source-android/androidnative.pri/tests/instrument/activity/activity.pro new file mode 100644 index 0000000..5014f6c --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/activity.pro @@ -0,0 +1,33 @@ +TEMPLATE = app + +QT += qml quick + +SOURCES += main.cpp \ + automator.cpp + +RESOURCES += qml.qrc + +# Additional import path used to resolve QML modules in Qt Creator's code model +# QML_IMPORT_PATH += ../.. + +android { + QT += androidextras + ANDROID_PACKAGE_SOURCE_DIR = $$PWD/android-sources +} + +include(../../../androidnative.pri) + +DISTFILES += \ + android-sources/AndroidManifest.xml \ + android-sources/src/quickandroid/example/ExampleService.java \ + README.md \ + android-sources/gradle/wrapper/gradle-wrapper.jar \ + android-sources/gradlew \ + android-sources/res/values/libs.xml \ + android-sources/build.gradle \ + android-sources/gradle/wrapper/gradle-wrapper.properties \ + android-sources/gradlew.bat \ + android-sources/settings.gradle + +HEADERS += \ + automator.h diff --git a/source-android/androidnative.pri/tests/instrument/activity/android-sources/AndroidManifest.xml b/source-android/androidnative.pri/tests/instrument/activity/android-sources/AndroidManifest.xml new file mode 100644 index 0000000..d123f0b --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/android-sources/AndroidManifest.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source-android/androidnative.pri/tests/instrument/activity/android-sources/build.gradle b/source-android/androidnative.pri/tests/instrument/activity/android-sources/build.gradle new file mode 100644 index 0000000..f25a7da --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/android-sources/build.gradle @@ -0,0 +1,86 @@ + +// Obtain androidPackageSourceDir +// androidPackageSourceDir is the absolute path of the folder containing build.gradle and AndroidManifests.xml +// This code also works with androiddeployqt. + +import groovy.json.JsonSlurper + +String getAndroidPackageSourceDir() { + String res = buildscript.sourceFile.getParent(); + + FileTree tree = fileTree(dir: res + "/..").include("android*deployment-settings.json"); + + if (tree.getFiles().size() > 0) { + def inputFile = tree.getFiles().toArray()[0]; + def InputJSON = new JsonSlurper().parseText(inputFile.text); + res = InputJSON["android-package-source-directory"] + } else { + println("android*deployment-settings.json not found. Set user.dir be the androidPackageSourceDir"); + } + + return res; +} + +String androidPackageSourceDir = getAndroidPackageSourceDir(); +println("androidPackageSourceDir = " + androidPackageSourceDir); + +// End of obtain androidPackageSourceDir + +buildscript { + repositories { + jcenter() + } + + dependencies { + classpath 'com.android.tools.build:gradle:1.3.0' + } +} + +allprojects { + repositories { + jcenter() + } +} + +apply plugin: 'com.android.application' + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) +} + +android { + /******************************************************* + * The following variables: + * - androidBuildToolsVersion, + * - androidCompileSdkVersion + * - qt5AndroidDir - holds the path to qt android files + * needed to build any Qt application + * on Android. + * + * are defined in gradle.properties file. This file is + * updated by QtCreator and androiddeployqt tools. + * Changing them manually might break the compilation! + *******************************************************/ + + compileSdkVersion 19 + + buildToolsVersion androidBuildToolsVersion + + sourceSets { + main { + manifest.srcFile 'AndroidManifest.xml' + java.srcDirs = [qt5AndroidDir + '/src', 'src', 'java', + androidPackageSourceDir + '/../../../../java/src'] + aidl.srcDirs = [qt5AndroidDir + '/src', 'src', 'aidl'] + res.srcDirs = [qt5AndroidDir + '/res', 'res'] + resources.srcDirs = ['src'] + renderscript.srcDirs = ['src'] + assets.srcDirs = ['assets'] + jniLibs.srcDirs = ['libs'] + } + } + + lintOptions { + abortOnError false + } +} diff --git a/source-android/androidnative.pri/tests/instrument/activity/android-sources/gradle/wrapper/gradle-wrapper.jar b/source-android/androidnative.pri/tests/instrument/activity/android-sources/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..8c0fb64 Binary files /dev/null and b/source-android/androidnative.pri/tests/instrument/activity/android-sources/gradle/wrapper/gradle-wrapper.jar differ diff --git a/source-android/androidnative.pri/tests/instrument/activity/android-sources/gradle/wrapper/gradle-wrapper.properties b/source-android/androidnative.pri/tests/instrument/activity/android-sources/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..b71827d --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/android-sources/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Jan 29 10:17:39 HKT 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip diff --git a/source-android/androidnative.pri/tests/instrument/activity/android-sources/gradlew b/source-android/androidnative.pri/tests/instrument/activity/android-sources/gradlew new file mode 100755 index 0000000..91a7e26 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/android-sources/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/source-android/androidnative.pri/tests/instrument/activity/android-sources/gradlew.bat b/source-android/androidnative.pri/tests/instrument/activity/android-sources/gradlew.bat new file mode 100644 index 0000000..aec9973 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/android-sources/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/source-android/androidnative.pri/tests/instrument/activity/android-sources/res/drawable/icon.png b/source-android/androidnative.pri/tests/instrument/activity/android-sources/res/drawable/icon.png new file mode 100644 index 0000000..156243d Binary files /dev/null and b/source-android/androidnative.pri/tests/instrument/activity/android-sources/res/drawable/icon.png differ diff --git a/source-android/androidnative.pri/tests/instrument/activity/android-sources/res/drawable/splash.xml b/source-android/androidnative.pri/tests/instrument/activity/android-sources/res/drawable/splash.xml new file mode 100644 index 0000000..c1bd6fc --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/android-sources/res/drawable/splash.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/source-android/androidnative.pri/tests/instrument/activity/android-sources/res/values/apptheme.xml b/source-android/androidnative.pri/tests/instrument/activity/android-sources/res/values/apptheme.xml new file mode 100644 index 0000000..455b965 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/android-sources/res/values/apptheme.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/source-android/androidnative.pri/tests/instrument/activity/android-sources/res/values/libs.xml b/source-android/androidnative.pri/tests/instrument/activity/android-sources/res/values/libs.xml new file mode 100644 index 0000000..4d68673 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/android-sources/res/values/libs.xml @@ -0,0 +1,25 @@ + + + + https://download.qt-project.org/ministro/android/qt5/qt-5.4 + + + + + + + + + + + + + + + + + + + + diff --git a/source-android/androidnative.pri/tests/instrument/activity/android-sources/src/quickandroid/example/ExampleService.java b/source-android/androidnative.pri/tests/instrument/activity/android-sources/src/quickandroid/example/ExampleService.java new file mode 100644 index 0000000..115beb0 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/android-sources/src/quickandroid/example/ExampleService.java @@ -0,0 +1,96 @@ +package quickandroid.example; +import androidnative.SystemDispatcher; +import android.app.Notification; +import android.app.NotificationManager; +import android.util.Log; +import android.os.Handler; +import android.app.Activity; +import android.view.View; +import android.content.Context; +import java.util.Map; +import org.qtproject.qt5.android.QtNative; + +public class ExampleService { + + static void start() { + + SystemDispatcher.addListener(new SystemDispatcher.Listener() { + + NotificationManager m_notificationManager; + Notification.Builder m_builder; + + private void notificationManagerNotify(Map data) { + + final Activity activity = QtNative.activity(); + final Map messageData = data; + + Runnable runnable = new Runnable () { + public void run() { + try { + String title = (String) messageData.get("title"); + + String message = (String) messageData.get("message"); + + if (m_notificationManager == null) { + m_notificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE); + m_builder = new Notification.Builder(activity); + + // Small Icon is a must to make notification works. + // And that is why you need to inherit QtActivity + m_builder.setSmallIcon(R.drawable.icon); + } + + m_builder.setContentTitle(title); + m_builder.setContentText(message); + m_notificationManager.notify(1, m_builder.build()); + + // Test function. Remove it later. + SystemDispatcher.dispatch("Notifier.notifyFinished"); + } catch (Exception e) { + Log.d("",e.getMessage()); + } + + }; + }; + activity.runOnUiThread(runnable); + } + + private void hapticFeedbackPerform(Map data) { + + final Activity activity = QtNative.activity(); + final Map messageData = data; + Runnable runnable = new Runnable () { + public void run() { + int feedbackConstant = (Integer) messageData.get("feedbackConstant"); + int flags = (Integer) messageData.get("flags"); + + Log.d("",String.format("hapticFeedbackPerform(%d,%d)",feedbackConstant,flags)); + + View rootView = activity.getWindow().getDecorView().getRootView(); + rootView.performHapticFeedback(feedbackConstant, flags); + + // Test function. Remove it later. + SystemDispatcher.dispatch("hapticFeedbackPerformFinished"); + }; + }; + activity.runOnUiThread(runnable); + } + + public void onDispatched(String name , Map data) { + + if (name.equals("Notifier.notify")) { + notificationManagerNotify(data); + return; + } else if (name.equals("hapticFeedbackPerform")) { + hapticFeedbackPerform(data); + return; + } + + return; + } + }); + + } + +} + diff --git a/source-android/androidnative.pri/tests/instrument/activity/automator.cpp b/source-android/androidnative.pri/tests/instrument/activity/automator.cpp new file mode 100644 index 0000000..3c61a6b --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/automator.cpp @@ -0,0 +1,30 @@ +#include +#include "AndroidNative/systemdispatcher.h" +#include "automator.h" + +using namespace AndroidNative; + +Automator::Automator(QObject *parent) : QObject(parent) +{ + +} + +Automator::~Automator() +{ + +} + +void Automator::start() +{ + connect(SystemDispatcher::instance(),SIGNAL(dispatched(QString,QVariantMap)), + this,SLOT(onDispatched(QString,QVariantMap))); +} + +void Automator::onDispatched(QString name, QVariantMap message) +{ + qDebug() << "Automator::receive" << name; + if (name == "Automater::echo") { + SystemDispatcher::instance()->dispatch("Automater::response",message); + } +} + diff --git a/source-android/androidnative.pri/tests/instrument/activity/automator.h b/source-android/androidnative.pri/tests/instrument/activity/automator.h new file mode 100644 index 0000000..9e8f71e --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/automator.h @@ -0,0 +1,27 @@ +#ifndef AUTOMATOR_H +#define AUTOMATOR_H + +#include +#include + +/// For unit test purpose. Not needed for regular project. + +class Automator : public QObject +{ + Q_OBJECT +public: + explicit Automator(QObject *parent = 0); + ~Automator(); + + void start(); + +signals: + +public slots: + +private slots: + void onDispatched(QString name,QVariantMap message); + +}; + +#endif // AUTOMATOR_H diff --git a/source-android/androidnative.pri/tests/instrument/activity/main.cpp b/source-android/androidnative.pri/tests/instrument/activity/main.cpp new file mode 100644 index 0000000..031e58b --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/main.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include +#include "automator.h" +#include "AndroidNative/systemdispatcher.h" + +#ifdef Q_OS_ANDROID +#include +#include + +using namespace AndroidNative; + +JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*) { + Q_UNUSED(vm); + qDebug("NativeInterface::JNI_OnLoad()"); + + // It must call this function within JNI_OnLoad to enable System Dispatcher + SystemDispatcher::registerNatives(); + + /* Optional: Register your own service */ + + // Call quickandroid.example.ExampleService.start() + QAndroidJniObject::callStaticMethod("quickandroid/example/ExampleService", + "start", + "()V"); + + return JNI_VERSION_1_6; +} +#endif + +int main(int argc, char *argv[]) +{ + QGuiApplication app(argc, argv); + + QQmlApplicationEngine engine; + + engine.addImportPath("qrc:///"); + engine.load(QUrl(QStringLiteral("qrc:///main.qml"))); + + /* Testing Code. Not needed for regular project */ + Automator* automator = new Automator(); + automator->start(); + + return app.exec(); +} diff --git a/source-android/androidnative.pri/tests/instrument/activity/main.qml b/source-android/androidnative.pri/tests/instrument/activity/main.qml new file mode 100644 index 0000000..92349ec --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/main.qml @@ -0,0 +1,4 @@ +import QtQuick 2.2 + +QtObject { +} diff --git a/source-android/androidnative.pri/tests/instrument/activity/qml.qrc b/source-android/androidnative.pri/tests/instrument/activity/qml.qrc new file mode 100644 index 0000000..5f6483a --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/activity/qml.qrc @@ -0,0 +1,5 @@ + + + main.qml + + diff --git a/source-android/androidnative.pri/tests/instrument/runner/AndroidManifest.xml b/source-android/androidnative.pri/tests/instrument/runner/AndroidManifest.xml new file mode 100644 index 0000000..56c21a1 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/runner/AndroidManifest.xml @@ -0,0 +1,21 @@ + + + + + + + + + + diff --git a/source-android/androidnative.pri/tests/instrument/runner/build.gradle b/source-android/androidnative.pri/tests/instrument/runner/build.gradle new file mode 100644 index 0000000..78b7205 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/runner/build.gradle @@ -0,0 +1,60 @@ +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.3.0' + } +} +apply plugin: 'com.android.application' + +dependencies { + compile fileTree(dir: 'libs', include: '*.jar') + compile project(':activity') +} + +task wrapper(type: Wrapper) { + gradleVersion = '2.9' //version required +} + +allprojects { + gradle.projectsEvaluated { + tasks.withType(JavaCompile) { +// options.compilerArgs << "-Xlint:deprecation" + } + } +} + +android { + compileSdkVersion 19 + buildToolsVersion "21.1.2" + + defaultConfig { + minSdkVersion 18 + targetSdkVersion 19 + } + + sourceSets { + main { + manifest.srcFile 'AndroidManifest.xml' + java.srcDirs = ['src' ] + resources.srcDirs = ['src'] + aidl.srcDirs = ['src'] + renderscript.srcDirs = ['src'] + res.srcDirs = ['res'] + assets.srcDirs = ['assets'] + } + + // Move the tests to tests/java, tests/res, etc... + instrumentTest.setRoot('tests') + + // Move the build types to build-types/ + // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ... + // This moves them out of them default location under src//... which would + // conflict with src/ being used by the main source set. + // Adding new build types or product flavors should be accompanied + // by a similar customization. + debug.setRoot('build-types/debug') + release.setRoot('build-types/release') + } +} diff --git a/source-android/androidnative.pri/tests/instrument/runner/build.xml b/source-android/androidnative.pri/tests/instrument/runner/build.xml new file mode 100644 index 0000000..0c30920 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/runner/build.xml @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source-android/androidnative.pri/tests/instrument/runner/gradle/wrapper/gradle-wrapper.jar b/source-android/androidnative.pri/tests/instrument/runner/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..9411448 Binary files /dev/null and b/source-android/androidnative.pri/tests/instrument/runner/gradle/wrapper/gradle-wrapper.jar differ diff --git a/source-android/androidnative.pri/tests/instrument/runner/gradle/wrapper/gradle-wrapper.properties b/source-android/androidnative.pri/tests/instrument/runner/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..384254c --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/runner/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Jan 29 17:43:25 HKT 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.9-all.zip diff --git a/source-android/androidnative.pri/tests/instrument/runner/gradlew b/source-android/androidnative.pri/tests/instrument/runner/gradlew new file mode 100755 index 0000000..9d82f78 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/runner/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/source-android/androidnative.pri/tests/instrument/runner/gradlew.bat b/source-android/androidnative.pri/tests/instrument/runner/gradlew.bat new file mode 100644 index 0000000..aec9973 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/runner/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/source-android/androidnative.pri/tests/instrument/runner/proguard-project.txt b/source-android/androidnative.pri/tests/instrument/runner/proguard-project.txt new file mode 100644 index 0000000..f2fe155 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/runner/proguard-project.txt @@ -0,0 +1,20 @@ +# To enable ProGuard in your project, edit project.properties +# to define the proguard.config property as described in that file. +# +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in ${sdk.dir}/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the ProGuard +# include property in project.properties. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/source-android/androidnative.pri/tests/instrument/runner/project.properties b/source-android/androidnative.pri/tests/instrument/runner/project.properties new file mode 100644 index 0000000..4ab1256 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/runner/project.properties @@ -0,0 +1,14 @@ +# 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 edit +# "ant.properties", and override values to adapt the script to your +# project structure. +# +# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): +#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt + +# Project target. +target=android-19 diff --git a/source-android/androidnative.pri/tests/instrument/runner/settings.gradle b/source-android/androidnative.pri/tests/instrument/runner/settings.gradle new file mode 100644 index 0000000..9f93991 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/runner/settings.gradle @@ -0,0 +1,2 @@ +include ":activity" +project(":activity").projectDir = new File("../build/android-build"); diff --git a/source-android/androidnative.pri/tests/instrument/runner/src/quickandroid/example/ExampleActivityTest.java b/source-android/androidnative.pri/tests/instrument/runner/src/quickandroid/example/ExampleActivityTest.java new file mode 100644 index 0000000..6dee8b3 --- /dev/null +++ b/source-android/androidnative.pri/tests/instrument/runner/src/quickandroid/example/ExampleActivityTest.java @@ -0,0 +1,315 @@ +package quickandroid.example; + +import android.app.Activity; +import android.app.Instrumentation; +import android.content.Intent; +import android.test.ActivityInstrumentationTestCase2; +import android.util.Log; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import androidnative.AndroidNativeActivity; +import androidnative.SystemDispatcher; + +/** + * This is a simple framework for a test of an Application. See + * {@link android.test.ApplicationTestCase ApplicationTestCase} for more information on + * how to write and extend Application tests. + *

+ * To run this test, you can type: + * adb shell am instrument -w \ + * -e class quickandroid.example.ExampleActivityTest \ + * quickandroid.example.tests/android.test.InstrumentationTestRunner + */ +public class ExampleActivityTest extends ActivityInstrumentationTestCase2 { + + private static String TAG = "ActivityTest"; + + public ExampleActivityTest() { + super(AndroidNativeActivity.class); + } + + private static boolean launched = false; + private static Activity mActivity = null; + + private void startActivity() { + if (launched) + return; + + Instrumentation instrumentation = getInstrumentation(); + Intent intent = new Intent(getInstrumentation() + .getTargetContext(), AndroidNativeActivity.class); + intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); + + mActivity = instrumentation.startActivitySync(intent); + launched = true; + + instrumentation.waitForIdleSync(); + sleep(5000); + } + + private int counter = 0; + + public void testDispatch() { + startActivity(); + + SystemDispatcher.Listener listener = new SystemDispatcher.Listener() { + + public void onDispatched(String name , Map data) { + Log.v(TAG,"Listener::onDispatched " + name); + + if (name.equals("testSendMessage")) { + counter++; + } + } + }; + + SystemDispatcher.addListener(listener); + assertTrue(counter == 0); + + SystemDispatcher.dispatch("testSendMessage",null); + + assertEquals(counter , 1); + + SystemDispatcher.removeListener(listener); + + SystemDispatcher.dispatch("testSendMessage",null); + assertTrue(counter == 1); + + } + + private List messages ; + + public void testDispatchReentrant() { + startActivity(); + Log.v(TAG,"testDispatchReentrant"); + messages = new ArrayList(); + + final String messageName = "testReentrant"; + + SystemDispatcher.Listener listener = new SystemDispatcher.Listener() { + + public void onDispatched(String name , Map data) { + messages.add(name); + if (name.equals("ping")) { + counter++; + SystemDispatcher.dispatch("pong"); + } else if (name.equals("poing")) { + counter++; + } + return; + } + }; + + SystemDispatcher.addListener(listener); + SystemDispatcher.addListener(listener); + + assertTrue(messages.size() == 0); + + SystemDispatcher.dispatch("ping",null); + assertEquals(messages.size() , 6); + assertTrue(messages.get(0).equals("ping")); + assertTrue(messages.get(1).equals("ping")); + assertTrue(messages.get(2).equals("pong")); + assertTrue(messages.get(3).equals("pong")); + assertTrue(messages.get(4).equals("pong")); + assertTrue(messages.get(5).equals("pong")); + + + SystemDispatcher.removeListener(listener); + SystemDispatcher.removeListener(listener); + } + + private static class Payload { + public String name; + public Map message; + } + + + private static Payload lastPayload; + + /** Verify the data convension function between C++ and Java */ + public void testDispatchTypes() { + startActivity(); + + Log.v(TAG,"testDispatchTypes"); + SystemDispatcher.Listener listener = new SystemDispatcher.Listener() { + + public void onDispatched(String type , Map message) { + Log.v(TAG,"testDispatchTypes - received: " + type); + + if (!type.equals("Automater::response")) { + return; + } + + Payload payload = new Payload(); + payload.name = type; + payload.message = message; + + lastPayload = payload; + } + }; + + SystemDispatcher.addListener(listener); + + Map message = new HashMap(); + message.put("field1","value1"); + message.put("field2",10); + message.put("field3",true); + message.put("field4",false); + + List field5 = new ArrayList(3); + field5.add(23); + field5.add(true); + field5.add("stringValue"); + message.put("field5",field5); + field5 = new ArrayList(10); + + Map field6 = new HashMap(); + field6.put("sfield1", "value1"); + field6.put("sfield2", 10); + field6.put("sfield3", true); + field6.put("sfield4", false); + message.put("field6", field6); + + assertTrue(lastPayload == null); + + SystemDispatcher.dispatch("Automater::echo",message); + sleep(500); + + assertTrue(lastPayload != null); + assertTrue(lastPayload.message.containsKey("field1")); + assertTrue(lastPayload.message.containsKey("field2")); + assertTrue(lastPayload.message.containsKey("field3")); + assertTrue(lastPayload.message.containsKey("field4")); + assertTrue(lastPayload.message.containsKey("field5")); + assertTrue(lastPayload.message.containsKey("field6")); + + String field1 = (String) lastPayload.message.get("field1"); + assertTrue(field1.equals("value1")); + + int field2 = (int) (Integer) lastPayload.message.get("field2"); + assertEquals(field2,10); + + boolean field3 = (boolean)(Boolean) lastPayload.message.get("field3"); + assertEquals(field3,true); + + boolean field4 = (boolean)(Boolean) lastPayload.message.get("field4"); + assertEquals(field4,false); + + List list = (List) lastPayload.message.get("field5"); + assertEquals(list.size(),3); + assertEquals(list.get(0), 23); + assertEquals(list.get(1), true); + assertTrue((((String) list.get(2)).equals("stringValue"))); + + Map map = (Map) lastPayload.message.get("field6"); + assertTrue(map.containsKey("sfield1")); + assertTrue(((String) map.get("sfield1")).equals("value1")); + assertTrue(map.containsKey("sfield2")); + assertEquals(map.get("sfield2"), 10); + assertTrue(map.containsKey("sfield3")); + assertTrue(map.containsKey("sfield4")); + + SystemDispatcher.removeListener(listener); + } + + public void testOnActivityResult() { + Log.v(TAG,"testOnActivityResult"); + startActivity(); + + SystemDispatcher.Listener listener = new SystemDispatcher.Listener() { + + public void onDispatched(String type , Map message) { + Log.v(TAG,"testOnActivityResult - received: " + type); + + Payload payload = new Payload(); + payload.name = type; + payload.message = message; + + lastPayload = payload; + } + }; + SystemDispatcher.addListener(listener); + + SystemDispatcher.dispatch("ping"); + + SystemDispatcher.onActivityResult(73, 99, null); + sleep(1500); + + assertTrue(lastPayload != null); + assertEquals(SystemDispatcher.ACTIVITY_RESULT_MESSAGE, lastPayload.name); + + assertTrue(lastPayload.message.containsKey("requestCode")); + assertTrue(lastPayload.message.containsKey("resultCode")); + assertTrue(lastPayload.message.containsKey("data")); + + assertEquals((int) (Integer) lastPayload.message.get("requestCode"), 73); + assertEquals((int) (Integer) lastPayload.message.get("resultCode") ,99); + + SystemDispatcher.removeListener(listener); + + } + + public void testHashTableOverflow() { + ArrayList list = new ArrayList(); + + int count = 600; + + for (int i = 0 ; i < count ; i++) { + HashMap map = new HashMap(); + map.put("value1", 1); + map.put("value2", true); + map.put("value3", "value3"); + + list.add(map); + } + + HashMap message = new HashMap(); + message.put("list", list); + + SystemDispatcher.Listener listener = new SystemDispatcher.Listener() { + + public void onDispatched(String name , Map message) { + + if (!name.equals("Automater::response")) { + return; + } + Payload payload = new Payload(); + payload.name = name; + payload.message = message; + + lastPayload = payload; + } + }; + + SystemDispatcher.addListener(listener); + SystemDispatcher.dispatch("Automater::echo", message); + + sleep(1500); + + assertTrue(lastPayload != null); + assertTrue(lastPayload.message.containsKey("list")); + + List retList = (List) lastPayload.message.get("list"); + + assertEquals(retList.size() , count); + + SystemDispatcher.removeListener(listener); + + } + + private void sleep(int timeout) { + try { + Thread.sleep(timeout); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + + +}