This commit is contained in:
LubuWest 2017-11-08 21:15:07 +01:00
parent 591d55f43a
commit fb560b54b1
115 changed files with 5537 additions and 0 deletions

View File

@ -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.

View File

@ -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 <AndroidNative>
// 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<T> |
| QVariantMap | Map<T> |
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)

View File

@ -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

View File

@ -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

View File

@ -0,0 +1,47 @@
#include <QtCore>
#include "debug.h"
#ifdef Q_OS_ANDROID
#include <QAndroidJniEnvironment>
#include <QAndroidJniObject>
#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
}

View File

@ -0,0 +1,18 @@
#ifndef DEBUG_H
#define DEBUG_H
namespace AndroidNative {
namespace Debug {
long getNativeHeapSize();
long getNativeHeapAllocatedSize();
}
}
#endif // DEBUG_H

View File

@ -0,0 +1,33 @@
#include <QStandardPaths>
#include <QDir>
#include "environment.h"
#ifdef Q_OS_ANDROID
#include <QAndroidJniEnvironment>
#include <QAndroidJniObject>
#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<jstring>("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;
}

View File

@ -0,0 +1,17 @@
#ifndef ENVIRONMENT_H
#define ENVIRONMENT_H
#include <QString>
namespace AndroidNative {
namespace Environment
{
extern QString DIRECTORY_DCIM;
QString getExternalStoragePublicDirectory(const QString& path);
};
}
#endif // ENVIRONMENT_H

View File

@ -0,0 +1,16 @@
#include "mediascannerconnection.h"
#include <AndroidNative/systemdispatcher.h>
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);
}

View File

@ -0,0 +1,14 @@
#ifndef MEDIASCANNERCONNECTION_H
#define MEDIASCANNERCONNECTION_H
#include <QString>
namespace AndroidNative {
namespace MediaScannerConnection
{
void scanFile(const QString& path);
}
}
#endif // MEDIASCANNERCONNECTION_H

View File

@ -0,0 +1,26 @@
#include <QtQml>
#include <AndroidNative/systemdispatcher.h>
#include <AndroidNative/priv/systemdispatcherproxy.h>
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<SystemDispatcherProxy>("AndroidNative", 1, 0,
"SystemDispatcher",
systemDispatcherProvider);
}
Q_COREAPP_STARTUP_FUNCTION(regiserQmlTypes)

View File

@ -0,0 +1,25 @@
#include <QtQml>
#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);
}

View File

@ -0,0 +1,23 @@
#pragma once
#include <QObject>
#include <QVariantMap>
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);
};
}

View File

@ -0,0 +1,373 @@
// Author: Ben Lau (https://github.com/benlau)
#include <QCoreApplication>
#include <QPointer>
#include <QtCore>
#include <QPair>
#include <QQueue>
#include "systemdispatcher.h"
using namespace AndroidNative;
static QPointer<SystemDispatcher> 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 <QAndroidJniObject>
#include <QAndroidJniEnvironment>
#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<jobject>(),jclass_of_boolean)) {
v = QVariant::fromValue<bool>(value.callMethod<jboolean>("booleanValue","()Z"));
} else if (env->IsInstanceOf(value.object<jobject>(),jclass_of_integer)) {
v = value.callMethod<jint>("intValue","()I");
} else if (env->IsInstanceOf(value.object<jobject>(),jclass_of_string)) {
v = value.toString();
} else if (env->IsInstanceOf(value.object<jobject>(), jclass_of_map)) {
v = createVariantMap(value.object<jobject>());
} else if (env->IsInstanceOf(value.object<jobject>(),jclass_of_list)) {
QVariantList list;
int count = value.callMethod<jint>("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, "<init>", "(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,"<init>","(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<QVariantList>();
jclass arrayListClass = env->FindClass("java/util/ArrayList");
jmethodID init = env->GetMethodID(arrayListClass, "<init>", "(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, "<init>", "(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<QString, QVariant> 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<void>(JCLASS_Name, "dispatch",
DISPATCH_SIGNATURE,
jType,jData);
env->DeleteLocalRef(jType);
env->DeleteLocalRef(jData);
#else
static bool dispatching = false;
static QQueue<QPair<QString,QVariantMap> > queue;
if (dispatching) {
queue.enqueue(QPair<QString,QVariantMap> (type,message) );
return;
}
dispatching = true;
emit dispatched(type,message);
while (queue.size() > 0) {
QPair<QString,QVariantMap> 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<void>(JCLASS_Name, "init",
"()V");
#endif
}

View File

@ -0,0 +1,50 @@
// Author: Ben Lau (https://github.com/benlau)
#pragma once
#include <QObject>
#include <QVariantMap>
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);
};
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

View File

@ -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
*/

View File

@ -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 <AndroidNative/systemdispatcher.h>
#include <QtAndroidExtras/QAndroidJniObject>
#include <QtAndroidExtras/QAndroidJniEnvironment>
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)

View File

@ -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 = \
" <link rel=\"stylesheet\" type=\"text/css\" href=\"style/offline.css\" />\n"

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

View File

@ -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
}
}

View File

@ -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)

View File

@ -0,0 +1,56 @@
<?xml version='1.0' encoding='utf-8'?>
<manifest package="androidnative.example" xmlns:android="http://schemas.android.com/apk/res/android" android:versionName="1.0" android:versionCode="1" android:installLocation="auto">
<application android:hardwareAccelerated="true"
android:name="org.qtproject.qt5.android.bindings.QtApplication"
android:theme="@style/AppTheme"
android:label="Android Native Example" android:icon="@drawable/icon">
<activity android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|locale|fontScale|keyboard|keyboardHidden|navigation"
android:name="androidnative.example.ExampleActivity"
android:label="Android Native Example"
android:screenOrientation="portrait"
android:theme="@style/AppTheme"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="android.app.lib_name" android:value="androidnativeexample"/>
<meta-data android:name="android.app.qt_sources_resource_id" android:resource="@array/qt_sources"/>
<meta-data android:name="android.app.repository" android:value="default"/>
<meta-data android:name="android.app.qt_libs_resource_id" android:resource="@array/qt_libs"/>
<meta-data android:name="android.app.bundled_libs_resource_id" android:resource="@array/bundled_libs"/>
<!-- Deploy Qt libs as part of package -->
<meta-data android:name="android.app.bundle_local_qt_libs" android:value="1"/>
<meta-data android:name="android.app.bundled_in_lib_resource_id" android:resource="@array/bundled_in_lib"/>
<meta-data android:name="android.app.bundled_in_assets_resource_id" android:resource="@array/bundled_in_assets"/>
<!-- Run with local libs -->
<meta-data android:name="android.app.use_local_qt_libs" android:value="1"/>
<meta-data android:name="android.app.libs_prefix" android:value="/data/local/tmp/qt/"/>
<meta-data android:name="android.app.load_local_libs" android:value="plugins/platforms/android/libqtforandroid.so:lib/libQt5QuickParticles.so"/>
<meta-data android:name="android.app.load_local_jars" android:value="jar/QtAndroid.jar:jar/QtAndroidAccessibility.jar:jar/QtAndroid-bundled.jar:jar/QtAndroidAccessibility-bundled.jar"/>
<meta-data android:name="android.app.static_init_classes" android:value=""/>
<!-- Messages maps -->
<meta-data android:value="@string/ministro_not_found_msg" android:name="android.app.ministro_not_found_msg"/>
<meta-data android:value="@string/ministro_needed_msg" android:name="android.app.ministro_needed_msg"/>
<meta-data android:value="@string/fatal_error_msg" android:name="android.app.fatal_error_msg"/>
<!-- Messages maps -->
<!-- Splash screen -->
<meta-data android:name="android.app.splash_screen_drawable" android:resource="@drawable/splash"/>
<!-- Splash screen -->
</activity>
</application>
<uses-sdk android:minSdkVersion="18" android:targetSdkVersion="21"/>
<supports-screens android:largeScreens="true" android:normalScreens="true" android:anyDensity="true" android:smallScreens="true"/>
<!-- The following comment will be replaced upon deployment with default permissions based on the dependencies of the application.
Remove the comment if you do not require these default permissions. -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- The following comment will be replaced upon deployment with default features based on the dependencies of the application.
Remove the comment if you do not require these default features. -->
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
</manifest>

View File

@ -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;
}

View File

@ -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("/../../..");

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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 "$@"

View File

@ -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

View File

@ -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

View File

@ -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

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle" >
<solid android:color="#FFFFFFFF"/>
</shape>
</item>
<item>
<bitmap android:src="@drawable/icon"
android:gravity="center" />
</item>
</layer-list>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="@android:style/Theme.DeviceDefault.Light.NoActionBar">
<item name="android:windowBackground">@drawable/splash</item>
</style>
</resources>

View File

@ -0,0 +1,25 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<array name="qt_sources">
<item>https://download.qt-project.org/ministro/android/qt5/qt-5.4</item>
</array>
<!-- The following is handled automatically by the deployment tool. It should
not be edited manually. -->
<array name="bundled_libs">
<!-- %%INSERT_EXTRA_LIBS%% -->
</array>
<array name="qt_libs">
<!-- %%INSERT_QT_LIBS%% -->
</array>
<array name="bundled_in_lib">
<!-- %%INSERT_BUNDLED_IN_LIB%% -->
</array>
<array name="bundled_in_assets">
<!-- %%INSERT_BUNDLED_IN_ASSETS%% -->
</array>
</resources>

View File

@ -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 = "";
}
}

View File

@ -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;
}
});
}
}

View File

@ -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

View File

@ -0,0 +1,392 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 4.4.0, 2017-10-23T22:04:08. -->
<qtcreator>
<data>
<variable>EnvironmentId</variable>
<value type="QByteArray">{8825bc46-5cad-4a59-be78-bf9eeaa7217a}</value>
</data>
<data>
<variable>ProjectExplorer.Project.ActiveTarget</variable>
<value type="int">0</value>
</data>
<data>
<variable>ProjectExplorer.Project.EditorSettings</variable>
<valuemap type="QVariantMap">
<value type="bool" key="EditorConfiguration.AutoIndent">true</value>
<value type="bool" key="EditorConfiguration.AutoSpacesForTabs">false</value>
<value type="bool" key="EditorConfiguration.CamelCaseNavigation">true</value>
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0">
<value type="QString" key="language">Cpp</value>
<valuemap type="QVariantMap" key="value">
<value type="QByteArray" key="CurrentPreferences">CppGlobal</value>
</valuemap>
</valuemap>
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.1">
<value type="QString" key="language">QmlJS</value>
<valuemap type="QVariantMap" key="value">
<value type="QByteArray" key="CurrentPreferences">QmlJSGlobal</value>
</valuemap>
</valuemap>
<value type="int" key="EditorConfiguration.CodeStyle.Count">2</value>
<value type="QByteArray" key="EditorConfiguration.Codec">UTF-8</value>
<value type="bool" key="EditorConfiguration.ConstrainTooltips">false</value>
<value type="int" key="EditorConfiguration.IndentSize">4</value>
<value type="bool" key="EditorConfiguration.KeyboardTooltips">false</value>
<value type="int" key="EditorConfiguration.MarginColumn">80</value>
<value type="bool" key="EditorConfiguration.MouseHiding">true</value>
<value type="bool" key="EditorConfiguration.MouseNavigation">true</value>
<value type="int" key="EditorConfiguration.PaddingMode">1</value>
<value type="bool" key="EditorConfiguration.ScrollWheelZooming">true</value>
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">0</value>
<value type="bool" key="EditorConfiguration.SmartSelectionChanging">true</value>
<value type="bool" key="EditorConfiguration.SpacesForTabs">true</value>
<value type="int" key="EditorConfiguration.TabKeyBehavior">0</value>
<value type="int" key="EditorConfiguration.TabSize">8</value>
<value type="bool" key="EditorConfiguration.UseGlobal">true</value>
<value type="int" key="EditorConfiguration.Utf8BomBehavior">1</value>
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
<value type="bool" key="EditorConfiguration.cleanIndentation">true</value>
<value type="bool" key="EditorConfiguration.cleanWhitespace">true</value>
<value type="bool" key="EditorConfiguration.inEntireDocument">false</value>
</valuemap>
</data>
<data>
<variable>ProjectExplorer.Project.PluginSettings</variable>
<valuemap type="QVariantMap"/>
</data>
<data>
<variable>ProjectExplorer.Project.Target.0</variable>
<valuemap type="QVariantMap">
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Android</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Android</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">{8e3757e7-5698-4d0f-9f13-55359b1a832e}</value>
<value type="int" key="ProjectExplorer.Target.ActiveBuildConfiguration">0</value>
<value type="int" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value>
<value type="int" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.0">
<value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory">/home/pankraz/build/debug</value>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">qmake</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">QtProjectManager.QMakeBuildStep</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibrary">true</value>
<value type="QString" key="QtProjectManager.QMakeBuildStep.QMakeArguments"></value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.QMakeForced">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.SeparateDebugInfo">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.UseQtQuickCompiler">false</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.1">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value>
<valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments">
<value type="QString">-w</value>
<value type="QString">-r</value>
</valuelist>
<value type="bool" key="Qt4ProjectManager.MakeStep.Clean">false</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments"></value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.2">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Anwendungsdaten kopieren</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.AndroidPackageInstallationStep</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.3">
<value type="QString" key="BuildTargetSdk">android-25</value>
<value type="QString" key="KeystoreLocation"></value>
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Android-APK erstellen</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">QmakeProjectManager.AndroidBuildApkStep</value>
<value type="int" key="Qt4ProjectManager.AndroidDeployQtStep.DeployQtAction">2</value>
<value type="bool" key="UseGradle">true</value>
<value type="bool" key="VerboseOutput">false</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">4</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Build</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value>
<valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments">
<value type="QString">-w</value>
<value type="QString">-r</value>
</valuelist>
<value type="bool" key="Qt4ProjectManager.MakeStep.Clean">true</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments">clean</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Bereinigen</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value>
<value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value>
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Debug</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.Qt4BuildConfiguration</value>
<value type="int" key="Qt4ProjectManager.Qt4BuildConfiguration.BuildConfiguration">2</value>
<value type="bool" key="Qt4ProjectManager.Qt4BuildConfiguration.UseShadowBuild">true</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.1">
<value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory">/home/pankraz/ownCloud/clientsync/Friendiqa/v0.005/source-android/androidnative.pri/examples/build-androidnativeexample-Android-Release</value>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">qmake</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">QtProjectManager.QMakeBuildStep</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibrary">false</value>
<value type="QString" key="QtProjectManager.QMakeBuildStep.QMakeArguments"></value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.QMakeForced">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.SeparateDebugInfo">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.UseQtQuickCompiler">false</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.1">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value>
<valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments">
<value type="QString">-w</value>
<value type="QString">-r</value>
</valuelist>
<value type="bool" key="Qt4ProjectManager.MakeStep.Clean">false</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments"></value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.2">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Anwendungsdaten kopieren</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.AndroidPackageInstallationStep</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.3">
<value type="QString" key="BuildTargetSdk">android-25</value>
<value type="QString" key="KeystoreLocation"></value>
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Android-APK erstellen</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">QmakeProjectManager.AndroidBuildApkStep</value>
<value type="int" key="Qt4ProjectManager.AndroidDeployQtStep.DeployQtAction">2</value>
<value type="bool" key="UseGradle">true</value>
<value type="bool" key="VerboseOutput">false</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">4</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Build</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value>
<valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments">
<value type="QString">-w</value>
<value type="QString">-r</value>
</valuelist>
<value type="bool" key="Qt4ProjectManager.MakeStep.Clean">true</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments">clean</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Bereinigen</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value>
<value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value>
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Release</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.Qt4BuildConfiguration</value>
<value type="int" key="Qt4ProjectManager.Qt4BuildConfiguration.BuildConfiguration">0</value>
<value type="bool" key="Qt4ProjectManager.Qt4BuildConfiguration.UseShadowBuild">true</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.2">
<value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory">/home/pankraz/ownCloud/clientsync/Friendiqa/v0.005/source-android/androidnative.pri/examples/build-androidnativeexample-Android-Profile</value>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">qmake</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">QtProjectManager.QMakeBuildStep</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibrary">true</value>
<value type="QString" key="QtProjectManager.QMakeBuildStep.QMakeArguments"></value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.QMakeForced">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.SeparateDebugInfo">true</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.UseQtQuickCompiler">false</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.1">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value>
<valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments">
<value type="QString">-w</value>
<value type="QString">-r</value>
</valuelist>
<value type="bool" key="Qt4ProjectManager.MakeStep.Clean">false</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments"></value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.2">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Anwendungsdaten kopieren</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.AndroidPackageInstallationStep</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.3">
<value type="QString" key="BuildTargetSdk">android-25</value>
<value type="QString" key="KeystoreLocation"></value>
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Android-APK erstellen</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">QmakeProjectManager.AndroidBuildApkStep</value>
<value type="int" key="Qt4ProjectManager.AndroidDeployQtStep.DeployQtAction">2</value>
<value type="bool" key="UseGradle">true</value>
<value type="bool" key="VerboseOutput">false</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">4</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Build</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value>
<valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments">
<value type="QString">-w</value>
<value type="QString">-r</value>
</valuelist>
<value type="bool" key="Qt4ProjectManager.MakeStep.Clean">true</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments">clean</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Bereinigen</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value>
<value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value>
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Profile</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.Qt4BuildConfiguration</value>
<value type="int" key="Qt4ProjectManager.Qt4BuildConfiguration.BuildConfiguration">0</value>
<value type="bool" key="Qt4ProjectManager.Qt4BuildConfiguration.UseShadowBuild">true</value>
</valuemap>
<value type="int" key="ProjectExplorer.Target.BuildConfigurationCount">3</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.DeployConfiguration.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Deployment auf Android-Gerät</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.AndroidDeployQtStep</value>
<value type="bool" key="UninstallPreviousPackage">false</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Deployment</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Deploy</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Deployment auf Android-Gerät</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Deployment auf Android-Gerät</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.AndroidDeployConfiguration2</value>
</valuemap>
<value type="int" key="ProjectExplorer.Target.DeployConfigurationCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.PluginSettings">
<value type="QString" key="AndroidDeviceSerialNumber">CB5A22HSB9</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.RunConfiguration.0">
<value type="bool" key="Analyzer.QmlProfiler.AggregateTraces">false</value>
<value type="bool" key="Analyzer.QmlProfiler.FlushEnabled">false</value>
<value type="uint" key="Analyzer.QmlProfiler.FlushInterval">1000</value>
<value type="QString" key="Analyzer.QmlProfiler.LastTraceFile"></value>
<value type="bool" key="Analyzer.QmlProfiler.Settings.UseGlobalSettings">true</value>
<valuelist type="QVariantList" key="Analyzer.Valgrind.AddedSuppressionFiles"/>
<value type="bool" key="Analyzer.Valgrind.Callgrind.CollectBusEvents">false</value>
<value type="bool" key="Analyzer.Valgrind.Callgrind.CollectSystime">false</value>
<value type="bool" key="Analyzer.Valgrind.Callgrind.EnableBranchSim">false</value>
<value type="bool" key="Analyzer.Valgrind.Callgrind.EnableCacheSim">false</value>
<value type="bool" key="Analyzer.Valgrind.Callgrind.EnableEventToolTips">true</value>
<value type="double" key="Analyzer.Valgrind.Callgrind.MinimumCostRatio">0.01</value>
<value type="double" key="Analyzer.Valgrind.Callgrind.VisualisationMinimumCostRatio">10</value>
<value type="bool" key="Analyzer.Valgrind.FilterExternalIssues">true</value>
<value type="int" key="Analyzer.Valgrind.LeakCheckOnFinish">1</value>
<value type="int" key="Analyzer.Valgrind.NumCallers">25</value>
<valuelist type="QVariantList" key="Analyzer.Valgrind.RemovedSuppressionFiles"/>
<value type="int" key="Analyzer.Valgrind.SelfModifyingCodeDetection">1</value>
<value type="bool" key="Analyzer.Valgrind.Settings.UseGlobalSettings">true</value>
<value type="bool" key="Analyzer.Valgrind.ShowReachable">false</value>
<value type="bool" key="Analyzer.Valgrind.TrackOrigins">true</value>
<value type="QString" key="Analyzer.Valgrind.ValgrindExecutable">valgrind</value>
<valuelist type="QVariantList" key="Analyzer.Valgrind.VisibleErrorKinds">
<value type="int">0</value>
<value type="int">1</value>
<value type="int">2</value>
<value type="int">3</value>
<value type="int">4</value>
<value type="int">5</value>
<value type="int">6</value>
<value type="int">7</value>
<value type="int">8</value>
<value type="int">9</value>
<value type="int">10</value>
<value type="int">11</value>
<value type="int">12</value>
<value type="int">13</value>
<value type="int">14</value>
</valuelist>
<valuelist type="QVariantList" key="Android.AmStartArgsKey"/>
<valuelist type="QVariantList" key="Android.PostFinishShellCmdListKey"/>
<valuelist type="QVariantList" key="Android.PreStartShellCmdListKey"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">androidnativeexample</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.AndroidRunConfiguration:/home/pankraz/ownCloud/clientsync/Friendiqa/v0.005/source-android/androidnative.pri/examples/androidnativeexample/androidnativeexample.pro</value>
<value type="QString" key="QMakeProjectManager.QmakeAndroidRunConfiguration.ProFile">androidnativeexample.pro</value>
<value type="uint" key="RunConfiguration.QmlDebugServerPort">3768</value>
<value type="bool" key="RunConfiguration.UseCppDebugger">false</value>
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>
<value type="bool" key="RunConfiguration.UseMultiProcess">false</value>
<value type="bool" key="RunConfiguration.UseQmlDebugger">false</value>
<value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value>
</valuemap>
<value type="int" key="ProjectExplorer.Target.RunConfigurationCount">1</value>
</valuemap>
</data>
<data>
<variable>ProjectExplorer.Project.TargetCount</variable>
<value type="int">1</value>
</data>
<data>
<variable>ProjectExplorer.Project.Updater.FileVersion</variable>
<value type="int">18</value>
</data>
<data>
<variable>Version</variable>
<value type="int">18</value>
</data>
</qtcreator>

View File

@ -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();
}

View File

@ -0,0 +1,20 @@
#ifndef DEBUGWRAPPER_H
#define DEBUGWRAPPER_H
#include <QObject>
class DebugWrapper : public QObject
{
Q_OBJECT
public:
explicit DebugWrapper(QObject *parent = 0);
signals:
public slots:
long getNativeHeapSize() const;
long getNativeHeapAllocatedSize() const;
};
#endif // DEBUGWRAPPER_H

View File

@ -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)

View File

@ -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"
}
}

View File

@ -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();
}
}
}
}
}

View File

@ -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
}
}

View File

@ -0,0 +1,72 @@
#include <QtCore>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQmlContext>
#include <QSettings>
//#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 <QtAndroidExtras/QAndroidJniObject>
#include <QtAndroidExtras/QAndroidJniEnvironment>
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();
}

View File

@ -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
<!-- Splash screen -->
<meta-data android:name="android.app.splash_screen_drawable" android:resource="@drawable/splash"/>
<!-- Splash screen -->
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
}
}

View File

@ -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!"
});
}
}
}

View File

@ -0,0 +1,31 @@
<RCC>
<qresource prefix="/">
<file>main.qml</file>
<file>res/drawable-hdpi/icon.png</file>
<file>Components.qml</file>
<file>res/drawable-xxhdpi/ic_menu.png</file>
<file>dialog/DialogDemo.qml</file>
<file>notification/NotificationDemo.qml</file>
<file>theme/AppTheme.qml</file>
<file>theme/qmldir</file>
<file>res/drawable-hdpi/ic_android_black_48dp.png</file>
<file>res/drawable-xxhdpi/ic_android_black_48dp.png</file>
<file>res/drawable-mdpi/ic_android_black_48dp.png</file>
<file>res/drawable-xhdpi/ic_android_black_48dp.png</file>
<file>res/drawable-xxxhdpi/ic_android_black_48dp.png</file>
<file>res/drawable-hdpi/ic_done_black_24dp.png</file>
<file>res/drawable-mdpi/ic_done_black_24dp.png</file>
<file>res/drawable-xhdpi/ic_done_black_24dp.png</file>
<file>res/drawable-xxhdpi/ic_done_black_24dp.png</file>
<file>res/drawable-xxxhdpi/ic_done_black_24dp.png</file>
<file>theme/ActionBarBackground.qml</file>
<file>res/drawable-xxhdpi/ic_keyboard_backspace.png</file>
<file>res/drawable-xxhdpi/ic_arrow_back.png</file>
<file>res/drawable-xxhdpi/ic_image.png</file>
<file>res/drawable-xxhdpi/ic_camera.png</file>
<file>imagePicker/ImagePickerDemo.qml</file>
<file>info/InfoDemo.qml</file>
<file>toast/ToastDemo.qml</file>
<file>statusbar/StatusBarDemo.qml</file>
</qresource>
</RCC>

View File

@ -0,0 +1,10 @@
{
"name": "",
"description": "",
"dependencies": [
"com.github.benlau.quickandroid@0.1.7"
],
"license": "NONE",
"pri_filename": "",
"webpage": ""
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 519 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 343 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 641 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 975 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 287 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 227 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 267 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 277 B

View File

@ -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");
}
}

View File

@ -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
}
}

View File

@ -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
}
}

View File

@ -0,0 +1,2 @@
module theme
singleton AppTheme 0.1 AppTheme.qml

View File

@ -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();
}
}
}

View File

@ -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();
}
}

View File

@ -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<Uri> list = new ArrayList(1);
list.add(uri);
importImageFromFileUri(list);
}
static private void importImageFromFileUri(List uris) {
Map reply = new HashMap();
ArrayList<String> 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<Uri> 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<Uri> 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);
}
}

View File

@ -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);
}
}

View File

@ -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<Payload> queue = new LinkedList();
private static List<Listener> listeners = new ArrayList<Listener>();
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<Map.Entry>) 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);
}
}
});
}
}

View File

@ -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));
}
}

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -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<Uri> list = new ArrayList(1);
list.add(uri);
importVideoFromFileUri(list);
}
static private void importVideoFromFileUri(List uris) {
Map reply = new HashMap();
ArrayList<String> list = new ArrayList(uris.size());
ArrayList<String> 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<Uri> 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<Uri> 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();
}
}
}

View File

@ -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");
}
}

View File

@ -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");
}
}

View File

@ -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");
}
}

View File

@ -0,0 +1,3 @@
ImagePicker 1.0 ImagePicker.qml
VideoPicker 1.0 VideoPicker.qml
Toast 1.0 Toast.qml

View File

@ -0,0 +1,8 @@
<RCC>
<qresource prefix="/qt-project.org/imports">
<file>AndroidNative/qmldir</file>
<file>AndroidNative/ImagePicker.qml</file>
<file>AndroidNative/Toast.qml</file>
<file>AndroidNative/VideoPicker.qml</file>
</qresource>
</RCC>

View File

@ -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": ""
}

View File

@ -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

View File

@ -0,0 +1,55 @@
<?xml version='1.0' encoding='utf-8'?>
<manifest package="quickandroid.example" xmlns:android="http://schemas.android.com/apk/res/android" android:versionName="1.0" android:versionCode="1" android:installLocation="auto">
<application android:hardwareAccelerated="true"
android:name="org.qtproject.qt5.android.bindings.QtApplication"
android:label="Quick Android Example" android:icon="@drawable/icon">
<activity android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|locale|fontScale|keyboard|keyboardHidden|navigation"
android:name="androidnative.AndroidNativeActivity"
android:label="Quick Android Example"
android:theme="@style/AppTheme"
android:screenOrientation="unspecified"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="android.app.lib_name" android:value="activity"/>
<meta-data android:name="android.app.qt_sources_resource_id" android:resource="@array/qt_sources"/>
<meta-data android:name="android.app.repository" android:value="default"/>
<meta-data android:name="android.app.qt_libs_resource_id" android:resource="@array/qt_libs"/>
<meta-data android:name="android.app.bundled_libs_resource_id" android:resource="@array/bundled_libs"/>
<!-- Deploy Qt libs as part of package -->
<meta-data android:name="android.app.bundle_local_qt_libs" android:value="1"/>
<meta-data android:name="android.app.bundled_in_lib_resource_id" android:resource="@array/bundled_in_lib"/>
<meta-data android:name="android.app.bundled_in_assets_resource_id" android:resource="@array/bundled_in_assets"/>
<!-- Run with local libs -->
<meta-data android:name="android.app.use_local_qt_libs" android:value="1"/>
<meta-data android:name="android.app.libs_prefix" android:value="/data/local/tmp/qt/"/>
<meta-data android:name="android.app.load_local_libs" android:value="plugins/platforms/android/libqtforandroid.so:lib/libQt5QuickParticles.so"/>
<meta-data android:name="android.app.load_local_jars" android:value="jar/QtAndroid.jar:jar/QtAndroidAccessibility.jar:jar/QtAndroid-bundled.jar:jar/QtAndroidAccessibility-bundled.jar"/>
<meta-data android:name="android.app.static_init_classes" android:value=""/>
<!-- Messages maps -->
<meta-data android:value="@string/ministro_not_found_msg" android:name="android.app.ministro_not_found_msg"/>
<meta-data android:value="@string/ministro_needed_msg" android:name="android.app.ministro_needed_msg"/>
<meta-data android:value="@string/fatal_error_msg" android:name="android.app.fatal_error_msg"/>
<!-- Messages maps -->
<!-- Splash screen -->
<meta-data android:name="android.app.splash_screen_drawable" android:resource="@drawable/splash"/>
<!-- Splash screen -->
</activity>
</application>
<uses-sdk android:minSdkVersion="18" android:targetSdkVersion="21"/>
<supports-screens android:largeScreens="true" android:normalScreens="true" android:anyDensity="true" android:smallScreens="true"/>
<!-- The following comment will be replaced upon deployment with default permissions based on the dependencies of the application.
Remove the comment if you do not require these default permissions. -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- The following comment will be replaced upon deployment with default features based on the dependencies of the application.
Remove the comment if you do not require these default features. -->
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
</manifest>

View File

@ -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
}
}

View File

@ -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

View File

@ -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 "$@"

View File

@ -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

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle" >
<solid android:color="#FFFFFFFF"/>
</shape>
</item>
<item>
<bitmap android:src="@drawable/icon"
android:gravity="center" />
</item>
</layer-list>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="@android:style/Theme.DeviceDefault.Light.NoActionBar">
<item name="android:windowBackground">@drawable/splash</item>
</style>
</resources>

View File

@ -0,0 +1,25 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<array name="qt_sources">
<item>https://download.qt-project.org/ministro/android/qt5/qt-5.4</item>
</array>
<!-- The following is handled automatically by the deployment tool. It should
not be edited manually. -->
<array name="bundled_libs">
<!-- %%INSERT_EXTRA_LIBS%% -->
</array>
<array name="qt_libs">
<!-- %%INSERT_QT_LIBS%% -->
</array>
<array name="bundled_in_lib">
<!-- %%INSERT_BUNDLED_IN_LIB%% -->
</array>
<array name="bundled_in_assets">
<!-- %%INSERT_BUNDLED_IN_ASSETS%% -->
</array>
</resources>

View File

@ -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;
}
});
}
}

View File

@ -0,0 +1,30 @@
#include <QtCore>
#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);
}
}

Some files were not shown because too many files have changed in this diff Show More