qint64 QSerialPortPrivate::writeToPort(const char *data, qint64 maxSize) { if (deviceId == BAD_PORT) { q_ptr->setError(QSerialPort::NotOpenError); return 0; } QAndroidJniEnvironment jniEnv; jbyteArray jarrayL = jniEnv->NewByteArray(maxSize); jniEnv->SetByteArrayRegion(jarrayL, 0, maxSize, (jbyte *)data); if (jniEnv->ExceptionCheck()) jniEnv->ExceptionClear(); int resultL = QAndroidJniObject::callStaticMethod<jint>( kJniClassName, "write", "(I[BI)I", deviceId, jarrayL, internalWriteTimeoutMsec); if (jniEnv->ExceptionCheck()) { jniEnv->ExceptionClear(); q_ptr->setErrorString(QStringLiteral("Writing to the device threw an exception")); jniEnv->DeleteLocalRef(jarrayL); return 0; } jniEnv->DeleteLocalRef(jarrayL); return resultL; }
LocalDeviceBroadcastReceiver::LocalDeviceBroadcastReceiver(QObject *parent) : AndroidBroadcastReceiver(parent), previousScanMode(0) { addAction(valueForStaticField(JavaNames::BluetoothDevice, JavaNames::ActionBondStateChanged)); addAction(valueForStaticField(JavaNames::BluetoothAdapter, JavaNames::ActionScanModeChanged)); addAction(valueForStaticField(JavaNames::BluetoothDevice, JavaNames::ActionAclConnected)); addAction(valueForStaticField(JavaNames::BluetoothDevice, JavaNames::ActionAclDisconnected)); if (QtAndroidPrivate::androidSdkVersion() >= 15) addAction(valueForStaticField(JavaNames::BluetoothDevice, JavaNames::ActionPairingRequest)); //API 15 //cache integer values for host & bonding mode //don't use the java fields directly but refer to them by name QAndroidJniEnvironment env; for (uint i = 0; i < (sizeof(hostModePreset)/sizeof(hostModePreset[0])); i++) { hostModePreset[i] = QAndroidJniObject::getStaticField<jint>( "android/bluetooth/BluetoothAdapter", scanModes[i]); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); hostModePreset[i] = 0; } } for (uint i = 0; i < (sizeof(bondingModePreset)/sizeof(bondingModePreset[0])); i++) { bondingModePreset[i] = QAndroidJniObject::getStaticField<jint>( "android/bluetooth/BluetoothDevice", bondModes[i]); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); bondingModePreset[i] = 0; } } }
bool QBluetoothSocketPrivate::setSocketDescriptor(const QAndroidJniObject &socket, QBluetoothServiceInfo::Protocol socketType_, QBluetoothSocket::SocketState socketState, QBluetoothSocket::OpenMode openMode) { Q_Q(QBluetoothSocket); if (q->state() != QBluetoothSocket::UnconnectedState || !socket.isValid()) return false; if (!ensureNativeSocket(socketType_)) return false; socketObject = socket; QAndroidJniEnvironment env; inputStream = socketObject.callObjectMethod("getInputStream", "()Ljava/io/InputStream;"); outputStream = socketObject.callObjectMethod("getOutputStream", "()Ljava/io/OutputStream;"); if (env->ExceptionCheck() || !inputStream.isValid() || !outputStream.isValid()) { env->ExceptionDescribe(); env->ExceptionClear(); //close socket again socketObject.callMethod<void>("close"); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); } socketObject = inputStream = outputStream = remoteDevice = QAndroidJniObject(); errorString = QBluetoothSocket::tr("Obtaining streams for service failed"); q->setSocketError(QBluetoothSocket::NetworkError); q->setSocketState(QBluetoothSocket::UnconnectedState); return false; } remoteDevice = socketObject.callObjectMethod("getRemoteDevice", "()Landroid/bluetooth/BluetoothDevice;"); if (inputThread) { inputThread->deleteLater(); inputThread = 0; } inputThread = new InputStreamThread(this); QObject::connect(inputThread, SIGNAL(dataAvailable()), q, SIGNAL(readyRead()), Qt::QueuedConnection); QObject::connect(inputThread, SIGNAL(error(int)), this, SLOT(inputThreadError(int)), Qt::QueuedConnection); inputThread->run(); q->setSocketState(socketState); q->setOpenMode(openMode | QIODevice::Unbuffered); if (openMode == QBluetoothSocket::ConnectedState) emit q->connected(); return true; }
void QASystemDispatcher::registerNatives() { #ifdef Q_OS_ANDROID QAndroidJniEnvironment env; jclass clazz = env->FindClass(JCLASS_Name); if (!clazz) { qCritical() << QString("Can't find %1 class").arg(QString(JCLASS_Name)); 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; } } #endif }
static bool registerNativeMethods() { JNINativeMethod methods[] { {"OnImageCaptured", "(ILjava/lang/String;)V", (void*)onImageCaptured} }; const char *classname = "an/qt/imageProcessor/ImageCaptureNative"; jclass clazz; QAndroidJniEnvironment env; QAndroidJniObject javaClass(classname); clazz = env->GetObjectClass(javaClass.object<jobject>()); //clazz = env->FindClass(classname); qDebug() << "find ImageCaptureNative - " << clazz; bool result = false; if(clazz) { jint ret = env->RegisterNatives(clazz, methods, sizeof(methods) / sizeof(methods[0])); env->DeleteLocalRef(clazz); qDebug() << "RegisterNatives return - " << ret; result = ret >= 0; } if(env->ExceptionCheck()) env->ExceptionClear(); return result; }
bool JniNative::registerNativeMethods() { JNINativeMethod methods[] { {"notifyMsg", "(III)V", (void*)notifyMsg}, {"setDirectBuffer","(Ljava/lang/Object;I)V",(void*)setDirectBuffer} }; const char *classname = "an/qt/useJar/ExtendsQtNative"; jclass clazz; QAndroidJniEnvironment env; QAndroidJniObject javaClass(classname); clazz = env->GetObjectClass(javaClass.object<jobject>()); // QDBG << "find ExtendsQtNative - " << clazz; bool result = false; if (clazz) { jint ret = env->RegisterNatives(clazz, methods, sizeof(methods) / sizeof(methods[0])); env->DeleteLocalRef(clazz); // QDBG << "RegisterNatives return - " << ret; result = ret >= 0; } if (env->ExceptionCheck()) env->ExceptionClear(); return result; }
void QLowEnergyControllerPrivate::readDescriptor( const QSharedPointer<QLowEnergyServicePrivate> service, const QLowEnergyHandle /*charHandle*/, const QLowEnergyHandle descriptorHandle) { Q_ASSERT(!service.isNull()); QAndroidJniEnvironment env; bool result = false; if (hub) { qCDebug(QT_BT_ANDROID) << "Read descriptor with handle" << descriptorHandle << service->uuid; result = hub->javaObject().callMethod<jboolean>("readDescriptor", "(I)Z", descriptorHandle); } if (env->ExceptionOccurred()) { env->ExceptionDescribe(); env->ExceptionClear(); result = false; } if (!result) service->setError(QLowEnergyService::DescriptorReadError); }
const QString Wpp::getDownloadPath() const { QString downloadPath; #if defined(Q_OS_ANDROID) //https://qt-project.org/forums/viewthread/35519 QAndroidJniObject mediaDir = QAndroidJniObject::callStaticObjectMethod("android/os/Environment", "getExternalStorageDirectory", "()Ljava/io/File;"); QAndroidJniObject mediaPath = mediaDir.callObjectMethod( "getAbsolutePath", "()Ljava/lang/String;" ); downloadPath = mediaPath.toString()+"/Download/"; QAndroidJniEnvironment env; if (env->ExceptionCheck()) { // Handle exception here. qDebug() << "[ERR]:Android(Extras):getting SD card download path"; env->ExceptionClear(); } #elif defined(Q_OS_IOS) QStringList paths = QStandardPaths::standardLocations(QStandardPaths::DownloadLocation); qDebug() << "[IOS]download paths count:" << paths.size(); downloadPath = paths.first(); #else QStringList paths = QStandardPaths::standardLocations(QStandardPaths::DownloadLocation); qDebug() << "[Other OS]download paths count:" << paths.size(); downloadPath = paths.first(); #endif qDebug() << "downloadPath:" << downloadPath; return downloadPath; }
QBluetoothDeviceDiscoveryAgentPrivate::QBluetoothDeviceDiscoveryAgentPrivate( const QBluetoothAddress &deviceAdapter, QBluetoothDeviceDiscoveryAgent *parent) : inquiryType(QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry), lastError(QBluetoothDeviceDiscoveryAgent::NoError), receiver(0), m_adapterAddress(deviceAdapter), m_active(NoScanActive), leScanTimeout(0), pendingCancel(false), pendingStart(false), lowEnergySearchTimeout(25000), q_ptr(parent) { QAndroidJniEnvironment env; adapter = QAndroidJniObject::callStaticObjectMethod("android/bluetooth/BluetoothAdapter", "getDefaultAdapter", "()Landroid/bluetooth/BluetoothAdapter;"); if (!adapter.isValid()) { if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); } qCWarning(QT_BT_ANDROID) << "Device does not support Bluetooth"; } }
void QLowEnergyControllerPrivate::readCharacteristic( const QSharedPointer<QLowEnergyServicePrivate> service, const QLowEnergyHandle charHandle) { Q_ASSERT(!service.isNull()); if (!service->characteristicList.contains(charHandle)) return; QAndroidJniEnvironment env; bool result = false; if (hub) { qCDebug(QT_BT_ANDROID) << "Read characteristic with handle" << charHandle << service->uuid; result = hub->javaObject().callMethod<jboolean>("readCharacteristic", "(I)Z", charHandle); } if (env->ExceptionOccurred()) { env->ExceptionDescribe(); env->ExceptionClear(); result = false; } if (!result) service->setError(QLowEnergyService::CharacteristicReadError); }
void QBluetoothSocketPrivate::inputThreadError(int errorCode) { Q_Q(QBluetoothSocket); if (errorCode != -1) { //magic error which is expected and can be ignored errorString = QBluetoothSocket::tr("Network error during read"); q->setSocketError(QBluetoothSocket::NetworkError); } //finally we can delete the InputStreamThread InputStreamThread *client = qobject_cast<InputStreamThread *>(sender()); if (client) client->deleteLater(); if (socketObject.isValid()) { //triggered when remote side closed the socket //cleanup internal objects //if it was call to local close()/abort() the objects are cleaned up already QAndroidJniEnvironment env; socketObject.callMethod<void>("close"); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); } inputStream = outputStream = remoteDevice = socketObject = QAndroidJniObject(); } q->setSocketState(QBluetoothSocket::UnconnectedState); q->setOpenMode(QIODevice::NotOpen); emit q->disconnected(); }
void QLowEnergyControllerPrivate::writeDescriptor( const QSharedPointer<QLowEnergyServicePrivate> service, const QLowEnergyHandle /*charHandle*/, const QLowEnergyHandle descHandle, const QByteArray &newValue) { Q_ASSERT(!service.isNull()); QAndroidJniEnvironment env; jbyteArray payload; payload = env->NewByteArray(newValue.size()); env->SetByteArrayRegion(payload, 0, newValue.size(), (jbyte *)newValue.constData()); bool result = false; if (hub) { qCDebug(QT_BT_ANDROID) << "Write descriptor with handle " << descHandle << newValue.toHex() << "(service:" << service->uuid << ")"; result = hub->javaObject().callMethod<jboolean>("writeDescriptor", "(I[B)Z", descHandle, payload); } if (env->ExceptionOccurred()) { env->ExceptionDescribe(); env->ExceptionClear(); result = false; } env->DeleteLocalRef(payload); if (!result) service->setError(QLowEnergyService::DescriptorWriteError); }
qint64 QBluetoothSocketPrivate::writeData(const char *data, qint64 maxSize) { //TODO implement buffered behavior (so far only unbuffered) Q_Q(QBluetoothSocket); if (state != QBluetoothSocket::ConnectedState || !outputStream.isValid()) { qCWarning(QT_BT_ANDROID) << "Socket::writeData: " << state << outputStream.isValid(); errorString = QBluetoothSocket::tr("Cannot write while not connected"); q->setSocketError(QBluetoothSocket::OperationError); return -1; } QAndroidJniEnvironment env; jbyteArray nativeData = env->NewByteArray((qint32)maxSize); env->SetByteArrayRegion(nativeData, 0, (qint32)maxSize, reinterpret_cast<const jbyte*>(data)); outputStream.callMethod<void>("write", "([BII)V", nativeData, 0, (qint32)maxSize); env->DeleteLocalRef(nativeData); emit q->bytesWritten(maxSize); if (env->ExceptionCheck()) { qCWarning(QT_BT_ANDROID) << "Error while writing"; env->ExceptionDescribe(); env->ExceptionClear(); errorString = QBluetoothSocket::tr("Error during write on socket."); q->setSocketError(QBluetoothSocket::NetworkError); return -1; } return maxSize; }
void AndroidMainWindow::fireSupportForumIntent() { #ifdef Q_OS_ANDROID // qDebug() << "fireSupportForumIntent()"; QAndroidJniObject s1 = QAndroidJniObject::fromString("http://mdforum.designer2k2.at/viewtopic.php?f=15&t=334"); QSettings settings; if ( settings.value("md/md", QVariant ( MDMODE ).toBool() ) == false ) { s1 = QAndroidJniObject::fromString("http://digifant-einzelabstimmung.de/bofh-ng/de/digifant-1/live-daten-auslesen"); } QAndroidJniObject::callStaticMethod<void>( "de/gummelinformatics/mui/MuiIntentHelper", "openUrl", "(Ljava/lang/String;)V", s1.object<jstring>() ); QAndroidJniEnvironment env; if (env->ExceptionCheck()) { // Handle exception here. qDebug() << "*** JNI exception ***"; env->ExceptionDescribe(); env->ExceptionClear(); env->ExceptionClear(); } else { qDebug() << "NO JNI exception"; } // QDesktopServices::openUrl( QUrl("http://mdforum.designer2k2.at/") ); #endif }
QString Wpp::createAlbumPath(const QString& albumName) { QString parentPath; #if defined(Q_OS_ANDROID) QAndroidJniObject Environment__MEDIA_MOUNTED = QAndroidJniObject::getStaticObjectField( "android/os/Environment", "MEDIA_MOUNTED", "Ljava/lang/String;"); qDebug() << "Environment__MEDIA_MOUNTED:isValid:" << Environment__MEDIA_MOUNTED.isValid() << ":toString:" << Environment__MEDIA_MOUNTED.toString(); QString Environment__MEDIA_MOUNTED_STRING = Environment__MEDIA_MOUNTED.toString(); QAndroidJniObject mediaState = QAndroidJniObject::callStaticObjectMethod("android/os/Environment", "getExternalStorageState", "()Ljava/lang/String;"); QString mediaStateString = mediaState.toString(); qDebug() <<"mediaStateString:"<< mediaStateString; if(mediaStateString != Environment__MEDIA_MOUNTED_STRING ) { qDebug() << "No SD Card..."; return QString(); } //https://qt-project.org/forums/viewthread/35519 QAndroidJniObject mediaDir = QAndroidJniObject::callStaticObjectMethod("android/os/Environment", "getExternalStorageDirectory", "()Ljava/io/File;"); QAndroidJniObject mediaPath = mediaDir.callObjectMethod( "getAbsolutePath", "()Ljava/lang/String;" ); parentPath = mediaPath.toString(); QAndroidJniEnvironment env; if (env->ExceptionCheck()) { // Handle exception here. qDebug() << "[ERR]:Android(Extras):getting SD card path"; env->ExceptionClear(); } #elif defined(Q_OS_IOS) QStringList paths = QStandardPaths::standardLocations(QStandardPaths::DataLocation); qDebug() << "[IOS]album parent paths count:" << paths.size(); parentPath = paths.first(); #else QStringList paths = QStandardPaths::standardLocations(QStandardPaths::DataLocation); qDebug() << "[Other OS]album parent paths count:" << paths.size(); parentPath = paths.first(); #endif QDir dir(parentPath); qDebug() << __FUNCTION__ << ":dir=" << dir.dirName(); QString userAlbumPath = parentPath.append("/").append(albumName);; QDir userAlbumDir = userAlbumPath; if( !userAlbumDir.exists() ) { qDebug() << albumName << ":not exists, create it"; dir.mkpath( albumName ); } else { qDebug() << albumName << ":exists"; } return userAlbumPath; }
void cleanJavaException() { QAndroidJniEnvironment env; if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); } }
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; } jclass integerClass = env->FindClass("java/lang/Integer"); jmethodID integerConstructor = env->GetMethodID(integerClass, "<init>", "(I)V"); jclass booleanClass = env->FindClass("java/lang/Boolean"); jmethodID booleanConstructor = env->GetMethodID(booleanClass,"<init>","(Z)V"); 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(); // qDebug() << iter.key() << iter.value(); QString key = iter.key(); jstring jkey = env->NewStringUTF(key.toLocal8Bit().data()); QVariant v = iter.value(); if (v.type() == QVariant::String) { QString str = v.toString(); jstring vString = env->NewStringUTF(str.toLocal8Bit().data()); env->CallObjectMethod(hashMap,put,jkey,vString); } else if (v.type() == QVariant::Int) { jobject integer = env->NewObject(integerClass,integerConstructor,v.toInt()); env->CallObjectMethod(hashMap,put,jkey,integer); } else if (v.type() == QVariant::Bool) { jobject boolean = env->NewObject(booleanClass,booleanConstructor,v.toBool()); env->CallObjectMethod(hashMap,put,jkey,boolean); } else { qWarning() << "QASystemDispatcher: Non-supported data type - " << v.type(); } } if (env->ExceptionOccurred()) { env->ExceptionDescribe(); env->ExceptionClear(); } return hashMap; }
void UnitsAttached::updateDPI() { if (m_screen == nullptr) { m_dpi = DEFAULT_DPI; return; } #if defined(Q_OS_IOS) // iOS integration of scaling (retina, non-retina, 4K) does itself. m_dpi = m_screen->physicalDotsPerInch(); #elif defined(Q_OS_ANDROID) // https://bugreports.qt-project.org/browse/QTBUG-35701 // recalculate dpi for Android QAndroidJniEnvironment env; QAndroidJniObject activity = QtAndroid::androidActivity(); QAndroidJniObject resources = activity.callObjectMethod("getResources", "()Landroid/content/res/Resources;"); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); m_dpi = DEFAULT_DPI; return; } QAndroidJniObject displayMetrics = resources.callObjectMethod("getDisplayMetrics", "()Landroid/util/DisplayMetrics;"); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); m_dpi = DEFAULT_DPI; return; } m_dpi = displayMetrics.getField<int>("densityDpi"); m_multiplier = displayMetrics.getField<float>("density"); #else // standard dpi m_dpi = m_screen->logicalDotsPerInch() * m_screen->devicePixelRatio(); #endif }
CBSettings::CBSettings(QObject *parent) : QObject(parent), settings("settings.ini",QSettings::IniFormat) { settings.setIniCodec("windows-1251"); if (settings.value(kIsFirstRan,true).toBool()){ // we have never use settings before,let's init them settings.setValue(kIsFirstRan,false); settings.setValue(kNeedCollect,true); #if defined(Q_OS_WIN32) || defined(Q_OS_MAC) || defined(Q_OS_IOS) QStringList paths = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation); if (!paths.empty()){ settings.setValue(kDefaultPath,"file:///"+paths.at(0)+"/Bases/"); } paths = QStandardPaths::standardLocations(QStandardPaths::DownloadLocation); if (!paths.empty()){ settings.setValue(kAttachSearchPath,"file:///"+paths.at(0)+"/"); } #endif #ifdef Q_OS_ANDROID QAndroidJniObject mediaDir = QAndroidJniObject::callStaticObjectMethod("android/os/Environment", "getExternalStorageDirectory", "()Ljava/io/File;"); QAndroidJniObject mediaPath = mediaDir.callObjectMethod( "getAbsolutePath", "()Ljava/lang/String;" ); QString dataAbsPath = "file://" + mediaPath.toString(); settings.setValue(kDefaultPath,dataAbsPath +"/Bases/"); settings.setValue(kAttachSearchPath,dataAbsPath+"/Downloads/"); QAndroidJniEnvironment env; if (env->ExceptionCheck()) { // Handle exception here. env->ExceptionClear(); } #endif } lastBasePath = settings.value(kLastBasePath,"").toString(); needCollect = settings.value(kNeedCollect,false).toBool(); m_defaultPath = settings.value(kDefaultPath,"").toString(); m_attachSearchPath = settings.value(kAttachSearchPath,"").toString(); int size = settings.beginReadArray(kRecent); for (int i = 0; i < size; ++i) { settings.setArrayIndex(i); QString name = settings.value(kBaseName).toString(); QString path = settings.value(kBasePath).toString(); recentBasesMap[name] = path; } settings.endArray(); emit recentBasesChanged(); }
void QSerialPortPrivate::setNativeMethods(void) { qCDebug(AndroidSerialPortLog) << "Registering Native Functions"; // REGISTER THE C++ FUNCTION WITH JNI JNINativeMethod javaMethods[] { {"nativeDeviceHasDisconnected", "(I)V", reinterpret_cast<void *>(jniDeviceHasDisconnected)}, {"nativeDeviceNewData", "(I[B)V", reinterpret_cast<void *>(jniDeviceNewData)}, {"nativeDeviceException", "(ILjava/lang/String;)V", reinterpret_cast<void *>(jniDeviceException)}, {"qgcLogDebug", "(Ljava/lang/String;)V", reinterpret_cast<void *>(jniLogDebug)}, {"qgcLogWarning", "(Ljava/lang/String;)V", reinterpret_cast<void *>(jniLogWarning)} }; QAndroidJniEnvironment jniEnv; if (jniEnv->ExceptionCheck()) { jniEnv->ExceptionDescribe(); jniEnv->ExceptionClear(); } jclass objectClass = jniEnv->FindClass(kJniClassName); if(!objectClass) { qWarning() << "Couldn't find class:" << kJniClassName; return; } jint val = jniEnv->RegisterNatives(objectClass, javaMethods, sizeof(javaMethods) / sizeof(javaMethods[0])); if (val < 0) { qWarning() << "Error registering methods: " << val; } else { qCDebug(AndroidSerialPortLog) << "Native Functions Registered"; } if (jniEnv->ExceptionCheck()) { jniEnv->ExceptionDescribe(); jniEnv->ExceptionClear(); } }
MyDevice::MyDevice(QObject *parent) : QObject(parent) { m_screen = qApp->primaryScreen(); m_dpi = m_screen->physicalDotsPerInch() * m_screen->devicePixelRatio(); m_isMobile = false; #if defined(Q_OS_IOS) m_dpi = m_screen->physicalDotsPerInch(); m_isMobile = true; #elif defined(Q_OS_ANDROID) QAndroidJniEnvironment env; QAndroidJniObject activity = QtAndroid::androidActivity(); QAndroidJniObject resources = activity.callObjectMethod("getResources", "()Landroid/content/res/Resources;"); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); //return EXIT_FAILURE; } QAndroidJniObject displayMetrics = resources.callObjectMethod("getDisplayMetrics", "()Landroid/util/DisplayMetrics;"); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); //return EXIT_FAILURE; } m_dpi = displayMetrics.getField<int>("densityDpi"); m_isMobile = true; #else // standard dpi m_dpi = m_screen->logicalDotsPerInch() * m_screen->devicePixelRatio(); #endif m_dp = m_dpi / 160.f; emit dpChanged(m_dp); emit isMobileChanged(m_isMobile); //qDebug() << "*** dp:"<<m_dp<<" dpi:"<<m_dpi; }
void Widget::onCaptureImage() { #ifdef ANDROID QAndroidJniObject::callStaticMethod<void>("an/qt/extendsQtWithJava/ExtendsQtWithJava", "captureImage"); QAndroidJniEnvironment env; if (env->ExceptionCheck()) { // Handle exception here. qDebug() << "Widget,onCaptureImage, got exception"; env->ExceptionDescribe(); env->ExceptionClear(); } #endif }
const char *system_default_filename(void) { /* Replace this when QtCore/QStandardPaths getExternalStorageDirectory landed */ QAndroidJniObject externalStorage = QAndroidJniObject::callStaticObjectMethod("android/os/Environment", "getExternalStorageDirectory", "()Ljava/io/File;"); QAndroidJniObject externalStorageAbsolute = externalStorage.callObjectMethod("getAbsolutePath", "()Ljava/lang/String;"); QString system_default_filename = externalStorageAbsolute.toString() + "/subsurface.xml"; QAndroidJniEnvironment env; if (env->ExceptionCheck()) { // FIXME: Handle exception here. env->ExceptionClear(); return strdup("/sdcard/subsurface.xml"); } return strdup(system_default_filename.toUtf8().data()); }
int HardwareUtilsAndroid::getNetworkStatus() { jint status = QAndroidJniObject::callStaticMethod<jint>("fr/calaos/calaoshome/HardwareUtils", "getNetworkStatus"); qDebug() << "Android: HardwareUtilsAndroid::getNetworkStatus(): " << status; //Clear exception if any QAndroidJniEnvironment env; if (env->ExceptionCheck()) { qDebug() << "JNI call failed"; env->ExceptionDescribe(); env->ExceptionClear(); } return status; }
void run() { // Example code to create WebView using C++ method. // However, it is not recommended to construct // everything using C++. It is very troublesome. // It just show how can you execute code with // Android application UI thread QAndroidJniEnvironment env; QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); QAndroidJniObject webView("android/webkit/WebView", "(Landroid/content/Context;)V", activity.object<jobject>()); QAndroidJniObject frameLayout = activity.callObjectMethod("findViewById","(I)Landroid/view/View;", 0x01020002); // Hard coded value of android.R.id.content QAndroidJniObject layout("android/widget/RelativeLayout", "(Landroid/content/Context;)V", activity.object<jobject>()); QAndroidJniObject params = QAndroidJniObject("android/view/ViewGroup$LayoutParams", "(II)V", (int) 0xffffffff, (int) 0xffffffff); layout.callMethod<void>("addView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V", webView.object<jobject>(), params.object<jobject>()); frameLayout.callMethod<void>("addView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V", layout.object<jobject>(), params.object<jobject>()); QAndroidJniObject url = QAndroidJniObject::fromString("http://qt-project.org"); webView.callMethod<void>("loadUrl","(Ljava/lang/String;)V",url.object<jstring>()); if (env->ExceptionOccurred()) { env->ExceptionDescribe(); env->ExceptionClear(); } }
void HardwareUtilsAndroid::showAlertMessage(QString title, QString message, QString buttontext) { QAndroidJniObject jTitle = QAndroidJniObject::fromString(title); QAndroidJniObject jMessage = QAndroidJniObject::fromString(message); QAndroidJniObject jButtontext = QAndroidJniObject::fromString(buttontext); QAndroidJniObject::callStaticMethod<void>("fr/calaos/calaoshome/HardwareUtils", "showAlertMessage", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", jTitle.object<jstring>(), jMessage.object<jstring>(), jButtontext.object<jstring>()); //Clear exception if any QAndroidJniEnvironment env; if (env->ExceptionCheck()) { qDebug() << "JNI call failed"; env->ExceptionDescribe(); env->ExceptionClear(); } }
void QLowEnergyControllerPrivate::writeCharacteristic( const QSharedPointer<QLowEnergyServicePrivate> service, const QLowEnergyHandle charHandle, const QByteArray &newValue, bool writeWithResponse) { //TODO don't ignore WriteWithResponse, right now we assume responses Q_ASSERT(!service.isNull()); if (!service->characteristicList.contains(charHandle)) return; QAndroidJniEnvironment env; jbyteArray payload; payload = env->NewByteArray(newValue.size()); env->SetByteArrayRegion(payload, 0, newValue.size(), (jbyte *)newValue.constData()); bool result = false; if (hub) { qCDebug(QT_BT_ANDROID) << "Write characteristic with handle " << charHandle << newValue.toHex() << "(service:" << service->uuid << ", writeWithResponse:" << writeWithResponse << ")"; result = hub->javaObject().callMethod<jboolean>("writeCharacteristic", "(I[BI)Z", charHandle, payload, writeWithResponse ? QLowEnergyService::WriteWithResponse : QLowEnergyService::WriteWithoutResponse); } if (env->ExceptionOccurred()) { env->ExceptionDescribe(); env->ExceptionClear(); result = false; } env->DeleteLocalRef(payload); if (!result) service->setError(QLowEnergyService::CharacteristicWriteError); }
void QBluetoothSocketPrivate::abort() { if (state == QBluetoothSocket::UnconnectedState) return; if (socketObject.isValid()) { QAndroidJniEnvironment env; /* * BluetoothSocket.close() triggers an abort of the input stream * thread because inputStream.read() throws IOException * In turn the thread stops and throws an error which sets * new state, error and emits relevant signals. * See QBluetoothSocketPrivate::inputThreadError() for details */ if (inputThread) inputThread->prepareForClosure(); //triggers abort of input thread as well socketObject.callMethod<void>("close"); if (env->ExceptionCheck()) { qCWarning(QT_BT_ANDROID) << "Error during closure of socket"; env->ExceptionDescribe(); env->ExceptionClear(); } if (inputThread) { //don't delete here as signals caused by Java Thread are still //going to be emitted //delete occurs in inputThreadError() inputThread = 0; } inputStream = outputStream = socketObject = remoteDevice = QAndroidJniObject(); } }
void QBluetoothServiceDiscoveryAgentPrivate::start(const QBluetoothAddress &address) { Q_Q(QBluetoothServiceDiscoveryAgent); if (!btAdapter.isValid()) { error = QBluetoothServiceDiscoveryAgent::UnknownError; errorString = QBluetoothServiceDiscoveryAgent::tr("Platform does not support Bluetooth"); //abort any outstanding discoveries discoveredDevices.clear(); emit q->error(error); _q_serviceDiscoveryFinished(); return; } /* SDP discovery was officially added by Android API v15 * BluetoothDevice.getUuids() existed in earlier APIs already and in the future we may use * reflection to support earlier Android versions than 15. Unfortunately * BluetoothDevice.fetchUuidsWithSdp() and related APIs had some structure changes * over time. Therefore we won't attempt this with reflection. * * TODO: Use reflection to support getUuuids() where possible. * */ if (QtAndroidPrivate::androidSdkVersion() < 15) { qCWarning(QT_BT_ANDROID) << "Aborting SDP enquiry due to too low Android API version (requires v15+)"; error = QBluetoothServiceDiscoveryAgent::UnknownError; errorString = QBluetoothServiceDiscoveryAgent::tr("Android API below v15 does not support SDP discovery"); //abort any outstanding discoveries sdpCache.clear(); discoveredDevices.clear(); emit q->error(error); _q_serviceDiscoveryFinished(); return; } QAndroidJniObject inputString = QAndroidJniObject::fromString(address.toString()); QAndroidJniObject remoteDevice = btAdapter.callObjectMethod("getRemoteDevice", "(Ljava/lang/String;)Landroid/bluetooth/BluetoothDevice;", inputString.object<jstring>()); QAndroidJniEnvironment env; if (env->ExceptionCheck()) { env->ExceptionClear(); env->ExceptionDescribe(); //if it was only device then its error -> otherwise go to next device if (singleDevice) { error = QBluetoothServiceDiscoveryAgent::InputOutputError; errorString = QBluetoothServiceDiscoveryAgent::tr("Cannot create Android BluetoothDevice"); qCWarning(QT_BT_ANDROID) << "Cannot start SDP for" << discoveredDevices.at(0).name() << "(" << address.toString() << ")"; emit q->error(error); } _q_serviceDiscoveryFinished(); return; } if (mode == QBluetoothServiceDiscoveryAgent::MinimalDiscovery) { qCDebug(QT_BT_ANDROID) << "Minimal discovery on (" << discoveredDevices.at(0).name() << ")" << address.toString() ; //Minimal discovery uses BluetoothDevice.getUuids() QAndroidJniObject parcelUuidArray = remoteDevice.callObjectMethod( "getUuids", "()[Landroid/os/ParcelUuid;"); if (!parcelUuidArray.isValid()) { if (singleDevice) { error = QBluetoothServiceDiscoveryAgent::InputOutputError; errorString = QBluetoothServiceDiscoveryAgent::tr("Cannot obtain service uuids"); emit q->error(error); } qCWarning(QT_BT_ANDROID) << "Cannot retrieve SDP UUIDs for" << discoveredDevices.at(0).name() << "(" << address.toString() << ")"; _q_serviceDiscoveryFinished(); return; } const QList<QBluetoothUuid> results = ServiceDiscoveryBroadcastReceiver::convertParcelableArray(parcelUuidArray); populateDiscoveredServices(discoveredDevices.at(0), results); _q_serviceDiscoveryFinished(); } else { qCDebug(QT_BT_ANDROID) << "Full discovery on (" << discoveredDevices.at(0).name() << ")" << address.toString(); //Full discovery uses BluetoothDevice.fetchUuidsWithSdp() if (!receiver) { receiver = new ServiceDiscoveryBroadcastReceiver(); QObject::connect(receiver, SIGNAL(uuidFetchFinished(QBluetoothAddress,QList<QBluetoothUuid>)), q, SLOT(_q_processFetchedUuids(QBluetoothAddress,QList<QBluetoothUuid>))); } if (!localDeviceReceiver) { localDeviceReceiver = new LocalDeviceBroadcastReceiver(); QObject::connect(localDeviceReceiver, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode)), q, SLOT(_q_hostModeStateChanged(QBluetoothLocalDevice::HostMode))); } jboolean result = remoteDevice.callMethod<jboolean>("fetchUuidsWithSdp"); if (!result) { //kill receiver to limit load of signals receiver->unregisterReceiver(); receiver->deleteLater(); receiver = 0; qCWarning(QT_BT_ANDROID) << "Cannot start dynamic fetch."; _q_serviceDiscoveryFinished(); } } }
void NativeDateTimePicker::open() { #ifdef Q_OS_ANDROID QAndroidJniObject activity = QtAndroid::androidActivity(); qDebug() << __FUNCTION__ << "activity.isValid()=" << activity.isValid(); //QAndroidJniObject str = QAndroidJniObject::callStaticObjectMethod( // "wpp/android/DatePickerDialog", "show", "(Landroid/content/Context;)Ljava/lang/String;", activity.object<jobject>()); //qDebug() << "str.isValid()=" << str.isValid(); QDateTime dateTime; dateTime.setTimeZone(QTimeZone("UTC")); dateTime.setTimeSpec(Qt::UTC); dateTime.setTime_t( this->dateTime().toTime_t() ); QAndroidJniObject initDateISO8601 = QAndroidJniObject::fromString( dateTime.toString(Qt::ISODate) ); qDebug() << "QT--initDateISO8601=" << initDateISO8601.toString(); qDebug() << "QT--ts=" << dateTime.toTime_t(); QAndroidJniObject timezoneId = QAndroidJniObject::fromString( QString( System::getSystemTimezoneId() ) ); qDebug() << "QT--timezoneId=" << timezoneId.toString(); jlong qmlDateTimePickerPtr = (jlong)this; QAndroidJniObject jsonStr = QAndroidJniObject::callStaticObjectMethod( "wpp/android/DatePickerDialog", "show", "(Landroid/app/Activity;Ljava/lang/String;Ljava/lang/String;J)Ljava/lang/String;", activity.object<jobject>(), initDateISO8601.object<jstring>(), timezoneId.object<jstring>(), qmlDateTimePickerPtr ); /*QAndroidJniObject jsonStr = activity.callObjectMethod( "showDatePickerDialog", "()Ljava/lang/String;" );*/ /*QAndroidJniObject::callStaticObjectMethod( "com/kuulabu/android/app/MainActivity", "showDatePickerDialog", "()Ljava/lang/String;", activity.object<jobject>());*/ qDebug() << "jsonStr.isValid()=" << jsonStr.isValid() << ",jsonStr=" << jsonStr.toString(); //QAndroidJniObject dialog( "wpp/android/DatePickerDialog", "(Landroid/content/Context;)V", activity.object<jobject>() ); //qDebug() << "dialog.isValid()=" << dialog.isValid(); //dialog.callMethod<void>("show","()V"); //qDebug() << "dialog show ends..."; QAndroidJniEnvironment env; if (env->ExceptionCheck()) { // Handle exception here. qDebug() << "Exception 1...."; env->ExceptionDescribe(); env->ExceptionClear(); } /*QAndroidJniObject::callStaticObjectMethod( "wpp/android/DatePickerDialog", "show", "(Landroid/content/Context;)V", activity.object<jobject>() );*/ /* //android.provider.MediaStore.EXTRA_OUTPUT QAndroidJniObject MediaStore__EXTRA_OUTPUT = QAndroidJniObject::getStaticObjectField( "android/provider/MediaStore", "EXTRA_OUTPUT", "Ljava/lang/String;"); qDebug() << "MediaStore__EXTRA_OUTPUT.isValid()=" << MediaStore__EXTRA_OUTPUT.isValid(); QAndroidJniObject action = QAndroidJniObject::fromString("android.media.action.IMAGE_CAPTURE"); QAndroidJniObject intent=QAndroidJniObject("android/content/Intent","(Ljava/lang/String;)V", action.object<jstring>()); qDebug() << __FUNCTION__ << "intent.isValid()=" << intent.isValid(); QAndroidJniObject extDir = QAndroidJniObject::callStaticObjectMethod( "android/os/Environment", "getExternalStorageDirectory", "()Ljava/io/File;"); qDebug() << "extDir.isValid()=" << extDir.isValid(); QAndroidJniObject filename = QAndroidJniObject::fromString("camera.jpg"); QAndroidJniObject photo=QAndroidJniObject("java/io/File","(Ljava/io/File;Ljava/lang/String;)V", extDir.object<jobject>(), filename.object<jstring>()); qDebug() << __FUNCTION__ << "photo.isValid()=" << photo.isValid(); takePhotoSavedUri = QAndroidJniObject::callStaticObjectMethod( "android/net/Uri", "fromFile", "(Ljava/io/File;)Landroid/net/Uri;", photo.object<jobject>()); qDebug() << "takePhotoSavedUri.isValid()=" << takePhotoSavedUri.isValid(); intent.callObjectMethod( "putExtra","(Ljava/lang/String;Landroid/os/Parcelable;)Landroid/content/Intent;", MediaStore__EXTRA_OUTPUT.object<jstring>(), takePhotoSavedUri.object<jobject>()); qDebug() << __FUNCTION__ << "intent.isValid()=" << intent.isValid(); int SHOOT_PHOTO = 1; QtAndroid::startActivity(intent, SHOOT_PHOTO, this);*/ #endif }