int ScreenValues::getResourceSize(const QString &resource) { #ifdef Q_OS_ANDROID QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); QAndroidJniObject resources = activity.callObjectMethod("getResources", "()Landroid/content/res/Resources;"); QAndroidJniObject jName = QAndroidJniObject::fromString(resource); QAndroidJniObject jDefType = QAndroidJniObject::fromString("dimen"); QAndroidJniObject jDefPackage = QAndroidJniObject::fromString("android"); jint identifier = resources.callMethod<jint>("getIdentifier", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I", jName.object<jstring>(), jDefType.object<jstring>(), jDefPackage.object<jstring>()); jint size = resources.callMethod<jint>("getDimensionPixelSize", "(I)I", identifier); return size; #else return 0; #endif }
int ScreenValues::retrieveDpi() { #ifdef Q_OS_ANDROID QAndroidJniEnvironment env; env->PushLocalFrame(9); QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); QAndroidJniObject resources = activity.callObjectMethod("getResources", "()Landroid/content/res/Resources;"); QAndroidJniObject displayMetrics = resources.callObjectMethod("getDisplayMetrics", "()Landroid/util/DisplayMetrics;"); jint densityDpi = displayMetrics.getField<jint>("densityDpi"); int result = (int)densityDpi; return result; #else return QGuiApplication::primaryScreen()->physicalDotsPerInch(); #endif }
void tst_QAndroidJniObject::callStaticBooleanMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Boolean"); QVERIFY(cls != 0); { QAndroidJniObject parameter = QAndroidJniObject::fromString("true"); QVERIFY(parameter.isValid()); jboolean b = QAndroidJniObject::callStaticMethod<jboolean>(cls, "parseBoolean", "(Ljava/lang/String;)Z", parameter.object<jstring>()); QVERIFY(b); } { QAndroidJniObject parameter = QAndroidJniObject::fromString("false"); QVERIFY(parameter.isValid()); jboolean b = QAndroidJniObject::callStaticMethod<jboolean>(cls, "parseBoolean", "(Ljava/lang/String;)Z", parameter.object<jstring>()); QVERIFY(!b); } }
void tst_QAndroidJniObject::compareOperatorTests() { QString str("hello!"); QAndroidJniObject stringObject = QAndroidJniObject::fromString(str); jobject obj = stringObject.object(); jobject jobj = stringObject.object<jobject>(); jstring jsobj = stringObject.object<jstring>(); QVERIFY(obj == stringObject); QVERIFY(jobj == stringObject); QVERIFY(stringObject == jobj); QVERIFY(jsobj == stringObject); QVERIFY(stringObject == jsobj); QAndroidJniObject stringObject3 = stringObject.object<jstring>(); QVERIFY(stringObject3 == stringObject); QAndroidJniObject stringObject2 = QAndroidJniObject::fromString(str); QVERIFY(stringObject != stringObject2); jstring jstrobj = 0; QAndroidJniObject invalidStringObject; QVERIFY(invalidStringObject == jstrobj); QVERIFY(jstrobj != stringObject); QVERIFY(stringObject != jstrobj); QVERIFY(!invalidStringObject.isValid()); }
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; }
wxString callActivityMethod_ss(const char *method, wxString parm) { wxString return_string; QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); if ( !activity.isValid() ){ qDebug() << "Activity is not valid"; return return_string; } // Need a Java environment to decode the resulting string if (java_vm->GetEnv( (void **) &jenv, JNI_VERSION_1_6) != JNI_OK) { qDebug() << "GetEnv failed."; return _T("jenv Error"); } jstring p = (jenv)->NewStringUTF(parm.c_str()); // Call the desired method QAndroidJniObject data = activity.callObjectMethod(method, "(Ljava/lang/String;)Ljava/lang/String;", p); jstring s = data.object<jstring>(); const char *ret_string = (jenv)->GetStringUTFChars(s, NULL); return_string = wxString(ret_string, wxConvUTF8); return return_string; }
bool Wpp::vibrate(long milliseconds) { #ifdef Q_OS_ANDROID //http://stackoverflow.com/questions/29644280/how-to-make-phone-vibrate-from-qt-android /* */ QAndroidJniObject activity = QtAndroid::androidActivity(); qDebug() << __FUNCTION__ << "activity.isValid()=" << activity.isValid(); QAndroidJniObject Context__VIBRATOR_SERVICE = QAndroidJniObject::getStaticObjectField( "android/content/Context", "VIBRATOR_SERVICE", "Ljava/lang/String;"); qDebug() << "Context__VIBRATOR_SERVICE.isValid()=" << Context__VIBRATOR_SERVICE.isValid(); QAndroidJniObject vibrator = activity.callObjectMethod("getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;", Context__VIBRATOR_SERVICE.object<jstring>()); if ( vibrator.isValid() ) { jlong ms = (jlong)milliseconds; qDebug() << "vibrator IS valid...:milliseconds=" << ms; vibrator.callMethod<void>("vibrate", "(J)V", milliseconds); return true; } else { qDebug() << "vibrator is NOT valid..."; return false; } #endif }
void Wpp::addToImageGallery(const QString& imageFullPath) { #if defined(Q_OS_ANDROID) /* http://stackoverflow.com/questions/2170214/image-saved-to-sdcard-doesnt-appear-in-androids-gallery-app File imageFile = ... MediaScannerConnection.scanFile(this, new String[] { imageFile.getPath() }, new String[] { "image/jpeg" }, null); */ QAndroidJniObject activity = QtAndroid::androidActivity(); qDebug() << __FUNCTION__ << "activity.isValid()=" << activity.isValid(); QAndroidJniEnvironment env; //new String[] { imageFile.getPath() } jobjectArray imageFilePaths = (jobjectArray)env->NewObjectArray( 1, env->FindClass("java/lang/String"), (jobject)0 ); QAndroidJniObject imagePathJString = QAndroidJniObject::fromString(imageFullPath); env->SetObjectArrayElement( imageFilePaths, 0, imagePathJString.object<jstring>() ); //new String[] { "image/jpeg", "image/png", "image/gif" } jobjectArray imageFileTypes = (jobjectArray)env->NewObjectArray( 3, env->FindClass("java/lang/String"), (jobject)0 ); QAndroidJniObject imageType1 = QAndroidJniObject::fromString("image/jpeg"); env->SetObjectArrayElement( imageFileTypes, 0, imageType1.object<jstring>() ); QAndroidJniObject imageType2 = QAndroidJniObject::fromString("image/png"); env->SetObjectArrayElement( imageFileTypes, 1, imageType2.object<jstring>() ); QAndroidJniObject imageType3 = QAndroidJniObject::fromString("image/gif"); env->SetObjectArrayElement( imageFileTypes, 2, imageType3.object<jstring>() ); QAndroidJniObject::callStaticMethod<void>("android/media/MediaScannerConnection", "scanFile", "(Landroid/content/Context;[Ljava/lang/String;[Ljava/lang/String;Landroid/media/MediaScannerConnection$OnScanCompletedListener;)V", activity.object<jobject>(), imageFilePaths, imageFileTypes, (jobject)0); env->DeleteLocalRef(imageFilePaths); env->DeleteLocalRef(imageFileTypes); #else #endif }
void tst_QAndroidJniObject::stringConvertionTest() { const QString qString(QLatin1String("Hello, Java")); QAndroidJniObject jString = QAndroidJniObject::fromString(qString); QVERIFY(jString.isValid()); QString qStringRet = jString.toString(); QCOMPARE(qString, qStringRet); }
static void keepScreenOn() { QAndroidJniObject activity = QtAndroid::androidActivity(); if (activity.isValid()) { QAndroidJniObject window = activity.callObjectMethod("getWindow", "()Landroid/view/Window;"); if (window.isValid()) { const int FLAG_KEEP_SCREEN_ON = 128; window.callMethod<void>("addFlags", "(I)V", FLAG_KEEP_SCREEN_ON); } } }
void tst_QAndroidJniObject::callObjectMethodTest() { const QString qString = QLatin1String("Hello, Java"); QAndroidJniObject jString = QAndroidJniObject::fromString(qString); const QString qStringRet = jString.callObjectMethod<jstring>("toUpperCase").toString(); QCOMPARE(qString.toUpper(), qStringRet); QAndroidJniObject subString = jString.callObjectMethod("substring", "(II)Ljava/lang/String;", 0, 4); QCOMPARE(subString.toString(), qString.mid(0, 4)); }
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 Wpp::enableAutoScreenOrientation(bool enable) { #ifdef Q_OS_ANDROID QAndroidJniObject activity = QtAndroid::androidActivity(); qDebug() << __FUNCTION__ << "activity.isValid()=" << activity.isValid(); QAndroidJniObject contentResolver = activity.callObjectMethod("getContentResolver","()Landroid/content/ContentResolver;"); qDebug() << __FUNCTION__ << "contentResolver.isValid()=" << contentResolver.isValid(); QAndroidJniObject Settings__System__ACCELEROMETER_ROTATION = QAndroidJniObject::getStaticObjectField( "android/provider/Settings$System", "ACCELEROMETER_ROTATION", "Ljava/lang/String;"); qDebug() << __FUNCTION__ << "ACCELEROMETER_ROTATION.isValid()=" << Settings__System__ACCELEROMETER_ROTATION.isValid(); jint orig = (bool)QAndroidJniObject::callStaticMethod<jint>( "android.provider.Settings$System", "getInt", "(Landroid/content/ContentResolver;Ljava/lang/String;)I", contentResolver.object<jobject>(), Settings__System__ACCELEROMETER_ROTATION.object<jstring>() ); qDebug() << "orig=" << orig; //Settings.Secure.getInt(mContentResolver,mSettingName bool r = (bool)QAndroidJniObject::callStaticMethod<jboolean>( "android.provider.Settings$System", "putInt", "(Landroid/content/ContentResolver;Ljava/lang/String;I)B", contentResolver.object<jobject>(), Settings__System__ACCELEROMETER_ROTATION.object<jstring>(), enable?1:0 ); qDebug() << __FUNCTION__ << ":r=" << r; /* http://stackoverflow.com/questions/3611457/android-temporarily-disable-orientation-changes-in-an-activity None of the other answers did the trick perfectly for me, but here's what I found that does. Lock orientation to current... if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); When changing orientation should be allowed again, set back to default... setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); */ #endif __IMPLEMENTATION_DETAIL_ENABLE_AUTO_ROTATE = enable; }
MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { //LITTLE HACK FOR KEEPING SCREEN ON QAndroidJniObject activity = QtAndroid::androidActivity(); if (activity.isValid()) { QAndroidJniObject window = activity.callObjectMethod("getWindow", "()Landroid/view/Window;"); if (window.isValid()) { window.callMethod<void>("setFlags", "(II)V", 128, 128); } } QPalette pal = palette(); pal.setBrush(QPalette::Background, QBrush(QPixmap(":/background.png"))); setPalette(pal); ball = new Ball(); scene = new Scene(); scene->addBall(ball); scene->setSceneRect(-200, -200, 400, 200000); connect(ball, &Ball::collision, scene, &Scene::gameOver); view = new View(scene, this); view->addBall(ball); view->centerOn(ball); connect(&scene->timer(), &QTimer::timeout, view, &View::updateBall); TimeCounter *timeCounter = new TimeCounter(this); connect(scene, &Scene::passed, timeCounter, &TimeCounter::addTime); connect(timeCounter, &TimeCounter::timesUp, scene, &Scene::gameOver); connect(ball, &Ball::collision, timeCounter, &TimeCounter::stop); PointCounter *pointCounter = new PointCounter(this); connect(scene, &Scene::passed, pointCounter, &PointCounter::addPoint); newGameButton = new QPushButton("Restart"); connect(newGameButton, &QPushButton::clicked, ball, &Ball::restart); connect(newGameButton, &QPushButton::clicked, scene, &Scene::resetScene); connect(newGameButton, &QPushButton::clicked, timeCounter, &TimeCounter::start); connect(newGameButton, &QPushButton::clicked, pointCounter, &PointCounter::resetPoints); QVBoxLayout *layout = new QVBoxLayout(); QHBoxLayout *hLayout = new QHBoxLayout(); hLayout->addWidget(timeCounter); hLayout->addWidget(pointCounter); layout->addLayout(hLayout); layout->addWidget(view); layout->addWidget(newGameButton); setLayout(layout); }
wxSize getAndroidDisplayDimensions( void ) { wxSize sz_ret = ::wxGetDisplaySize(); // default, probably reasonable, but maybe not accurate QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); if ( !activity.isValid() ){ qDebug() << "Activity is not valid"; return sz_ret; } // Call the desired method QAndroidJniObject data = activity.callObjectMethod("getDisplayMetrics", "()Ljava/lang/String;"); wxString return_string; jstring s = data.object<jstring>(); // Need a Java environment to decode the resulting string if (java_vm->GetEnv( (void **) &jenv, JNI_VERSION_1_6) != JNI_OK) { qDebug() << "GetEnv failed."; } else { const char *ret_string = (jenv)->GetStringUTFChars(s, NULL); return_string = wxString(ret_string, wxConvUTF8); } wxStringTokenizer tk(return_string, _T(";")); if( tk.HasMoreTokens() ){ wxString token = tk.GetNextToken(); // xdpi token = tk.GetNextToken(); // density token = tk.GetNextToken(); // densityDPI token = tk.GetNextToken(); long a = ::wxGetDisplaySize().x; // default is wxWidgets idea if(token.ToLong( &a )) sz_ret.x = a; token = tk.GetNextToken(); long b = ::wxGetDisplaySize().y; if(token.ToLong( &b )) sz_ret.y = b; } wxSize sz_wx = ::wxGetDisplaySize(); // default, probably reasonable, but maybe not accurate qDebug() << sz_wx.x << sz_wx.y << sz_ret.x << sz_ret.y; return sz_ret; }
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()); }
void QQmlAndroidImageView::setImageURI(const QUrl &uri) { if (m_uri != uri) { m_uri = uri; if (isValid()) { QAndroidJniObject v = instance(); QAndroidJniObject u = getUri(); QtQmlAndroid::callFunction([=]() { v.callMethod<void>("setImageURI", "(Landroid/net/Uri;)V", u.object()); }); } emit imageURIChanged(); } }
void PaymentAndroid::callPaymentRequest() { QAndroidJniObject prIntent = m_class.callObjectMethod("paymentRequest", "(Landroid/content/Context;)Landroid/content/Intent;", QtAndroid::androidActivity().object<jobject>()); if(!prIntent.isValid()){ qCritical() << "Wrong intent"; return; } QtAndroid::startActivity(prIntent.object<jobject>(), ACTIVITY_REQUEST_CODE_PAYMENT); // QtAndroid::androidActivity().callObjectMethod("startActivity","(Landroid/content/Intent;)V", prIntent.object<jobject>()); }
bool androidGetMemoryStatus( int *mem_total, int *mem_used ) { // On android, We arbitrarilly declare that we have used 50% of available memory. if(mem_total) *mem_total = 100 * 1024; if(mem_used) *mem_used = 50 * 1024; return true; #if 0 // Get a reference to the running native activity QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); if ( !activity.isValid() ){ qDebug() << "Activity is not valid"; return false; } unsigned long android_processID = wxGetProcessId(); // Call the desired method QAndroidJniObject data = activity.callObjectMethod("getMemInfo", "(I)Ljava/lang/String;", (int)android_processID); // wxString return_string; jstring s = data.object<jstring>(); int mu = 50; // Need a Java environment to decode the resulting string if (java_vm->GetEnv( (void **) &jenv, JNI_VERSION_1_6) != JNI_OK) { qDebug() << "GetEnv failed."; } else { const char *ret_string = (jenv)->GetStringUTFChars(s, NULL); mu = atoi(ret_string); } if(mem_used) *mem_used = mu; return true; #endif }
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 tst_QAndroidJniObject::callStaticObjectMethodClassName() { QAndroidJniObject formatString = QAndroidJniObject::fromString(QLatin1String("test format")); QVERIFY(formatString.isValid()); QVERIFY(QAndroidJniObject::isClassAvailable("java/lang/String")); QAndroidJniObject returnValue = QAndroidJniObject::callStaticObjectMethod("java/lang/String", "format", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", formatString.object<jstring>(), jobjectArray(0)); QVERIFY(returnValue.isValid()); QString returnedString = returnValue.toString(); QCOMPARE(returnedString, QString::fromLatin1("test format")); }
void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data) { if(resultCode == -1 && GalleryResultReceiver::ReceiverRequestCode == receiverRequestCode) { if(data.isValid()) { // android/net/Uri // android/net/Uri getData() QAndroidJniObject uri = data.callObjectMethod("getData", "()Landroid/net/Uri;"); notify->finished(getLocalPathFromUri(uri)); } else { notify->error("Data isn't valid"); } } else { notify->error(QString("resultCode:%1, Data: %2").arg(resultCode).arg(data.toString())); } }
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 IOSTimeZonePicker::open() { #ifdef Q_OS_ANDROID QAndroidJniObject activity = QtAndroid::androidActivity(); qDebug() << __FUNCTION__ << "activity.isValid()=" << activity.isValid(); /* //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 }
void Wpp::setAppIconUnreadCount(int count) { #ifdef Q_OS_ANDROID QAndroidJniObject activity = QtAndroid::androidActivity(); qDebug() << __FUNCTION__ << "activity.isValid()=" << activity.isValid(); // ShortcutBadger.with(getApplicationContext()).count(badgeCount); QAndroidJniObject shortcutBadger = QAndroidJniObject::callStaticObjectMethod( "me/leolin/shortcutbadger/ShortcutBadger", "with", "(Landroid/content/Context;)Lme/leolin/shortcutbadger/ShortcutBadger;", activity.object<jobject>()); qDebug() << __FUNCTION__ << "shortcutBadger.isValid()=" << shortcutBadger.isValid(); shortcutBadger.callMethod<void>("count","(I)V",count); #endif }
bool Wpp::dial(const QString& phone, bool direct) { #ifdef Q_OS_ANDROID /* * http://stackoverflow.com/questions/5230912/android-app-to-call-a-number-on-button-click Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:"+txtPhn.getText().toString())); startActivity(callIntent); */ //发送号码到打电话那里 // Uri uri = Uri.parse("tel:XXXXXXX"); // Intent intent = new Intent(Intent.ACTION_DIAL,uri);//直接拨打:ACTION_CALL, 弹出窗口:ACTION_DIAL // // 或者Intent intent = new Intent("android.intent.action.DIAL"); // // Intent.ACTION_DIAL是内置常量,值为"android.intent.action.DIAL" // m_instance.startActivity(intent); QString uriQString("tel:"); uriQString.append( phone ); QAndroidJniObject uriString = QAndroidJniObject::fromString(uriQString); QAndroidJniObject uri = QAndroidJniObject::callStaticObjectMethod( "android/net/Uri", "parse", "(Ljava/lang/String;)Landroid/net/Uri;", uriString.object<jstring>()); qDebug() << "uri.isValid()=" << uri.isValid(); QAndroidJniObject Intent__ACTION_DIAL = QAndroidJniObject::getStaticObjectField( "android/content/Intent", "ACTION_DIAL", "Ljava/lang/String;"); qDebug() << "Intent__ACTION_DIAL.isValid()=" << Intent__ACTION_DIAL.isValid(); QAndroidJniObject Intent__ACTION_CALL = QAndroidJniObject::getStaticObjectField( "android/content/Intent", "ACTION_CALL", "Ljava/lang/String;"); qDebug() << "Intent__ACTION_CALL.isValid()=" << Intent__ACTION_CALL.isValid(); QAndroidJniObject intent=QAndroidJniObject("android/content/Intent","(Ljava/lang/String;Landroid/net/Uri;)V", direct? Intent__ACTION_CALL.object<jstring>() : Intent__ACTION_DIAL.object<jstring>(), uri.object<jobject>()); qDebug() << __FUNCTION__ << "intent.isValid()=" << intent.isValid(); QtAndroid::startActivity(intent, 0, 0); #endif }
void QQmlAndroidScrollView::onInflate(QAndroidJniObject &instance) { QQmlAndroidFrameLayout::onInflate(instance); static bool nativeMethodsRegistered = false; if (!nativeMethodsRegistered) { onRegisterNativeMethods(instance.object()); nativeMethodsRegistered = true; } }
void AndroidRfComm::check(const char* method, const QAndroidJniObject& obj) { if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); qCritical("Exception in %s",method); } else if (!obj.isValid()) { qCritical("Invalid object in %s",method); } }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; QQmlContext *context = engine.rootContext(); HousetrailModel aHouseTrailImages; Dialog dialog(&aHouseTrailImages); QSortFilterProxyModel detailsProxyModel; detailsProxyModel.setFilterRole(HousetrailModel::HousetrailRoles::CategoryRole); // MyViewModel::MyViewModel_Roles::MyViewModel_Roles_Details); //detailsProxyModel->setFilterRegExp( "^\\S+$" ); detailsProxyModel.setSourceModel(&aHouseTrailImages); qreal dpi; #if defined(Q_OS_ANDROID) QAndroidJniObject qtActivity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); QAndroidJniObject resources = qtActivity.callObjectMethod("getResources","()Landroid/content/res/Resources;"); QAndroidJniObject displayMetrics = resources.callObjectMethod("getDisplayMetrics","()Landroid/util/DisplayMetrics;"); int density = displayMetrics.getField<int>("densityDpi"); dpi = density; // qreal dpiRef = 132; //reference device dpi (ipad); // if(densitydpi > 0 && dpiRef > 0) // density = densitydpi / dpiRef; #else dpi = app.primaryScreen()->physicalDotsPerInch() * app.devicePixelRatio(); #endif // channel.registerObject(QStringLiteral("dialog"), &dialog); context->setContextProperty(QStringLiteral("dialog"), &dialog); context->setContextProperty(QStringLiteral("houseTrailModel"), &aHouseTrailImages); context->setContextProperty(QStringLiteral("filteredTrailModel"), &detailsProxyModel); context->setContextProperty(QStringLiteral("screenDpi"), dpi); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); }
QList<QSerialPortInfo> availablePortsByFiltersOfDevices(bool &ok) { QList<QSerialPortInfo> serialPortInfoList; //__android_log_print(ANDROID_LOG_INFO, V_TAG, "Collecting device list"); QAndroidJniObject resultL = QAndroidJniObject::callStaticObjectMethod( V_jniClassName, "availableDevicesInfo", "()[Ljava/lang/String;"); if (!resultL.isValid()) { __android_log_print(ANDROID_LOG_ERROR, V_TAG, "Error from availableDevicesInfo"); ok = false; return serialPortInfoList; } QAndroidJniEnvironment envL; jobjectArray objArrayL = resultL.object<jobjectArray>(); int countL = envL->GetArrayLength(objArrayL); for (int iL = 0; iL < countL; iL++) { QSerialPortInfoPrivate priv; jstring stringL = (jstring)(envL->GetObjectArrayElement(objArrayL, iL)); const char *rawStringL = envL->GetStringUTFChars(stringL, 0); //__android_log_print(ANDROID_LOG_INFO, V_TAG, "Adding device: %s", rawStringL); QStringList strListL = QString::fromUtf8(rawStringL).split(QStringLiteral(":")); envL->ReleaseStringUTFChars(stringL, rawStringL); priv.portName = strListL[0]; priv.device = strListL[0]; priv.manufacturer = strListL[1]; priv.productIdentifier = strListL[2].toInt(); priv.hasProductIdentifier = (priv.productIdentifier != 0) ? true: false; priv.vendorIdentifier = strListL[3].toInt(); priv.hasVendorIdentifier = (priv.vendorIdentifier != 0) ? true: false; serialPortInfoList.append(priv); } return serialPortInfoList; }