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 }
void ScreenValues::updateScreenValues() { #ifdef Q_OS_ANDROID if (m_system.sdkInt() >= 19) { QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); QAndroidJniObject wm = activity.callObjectMethod("getWindowManager", "()Landroid/view/WindowManager;"); QAndroidJniObject display = wm.callObjectMethod("getDefaultDisplay", "()Landroid/view/Display;"); QAndroidJniObject realSize = QAndroidJniObject("android/graphics/Point"); display.callMethod<void>("getRealSize", "(Landroid/graphics/Point;)V", realSize.object()); QAndroidJniObject displayFrame = QAndroidJniObject("android/graphics/Rect"); QAndroidJniObject window = activity.callObjectMethod("getWindow", "()Landroid/view/Window;"); QAndroidJniObject view = window.callObjectMethod("getDecorView", "()Landroid/view/View;"); QAndroidJniObject rootView = view.callObjectMethod("getRootView", "()Landroid/view/View;"); rootView.callMethod<void>("getWindowVisibleDisplayFrame", "(Landroid/graphics/Rect;)V", displayFrame.object()); if (((int) realSize.getField<jint>("y") - (int) displayFrame.callMethod<jint>("height")) - m_statusBarHeight == 0) setNavBarVisible(false); else setNavBarVisible(true); } #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 }
MarbleMaps::MarbleMaps(QQuickItem *parent) : MarbleQuickItem(parent), m_suspended(false) { QGuiApplication* application = qobject_cast<QGuiApplication*>(QGuiApplication::instance()); if (application) { connect(application, SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, SLOT(handleApplicationStateChange(Qt::ApplicationState))); } #ifdef Q_OS_ANDROID // If a file is passed, open it. Possible file types are registered in package/AndroidManifest.xml QAndroidJniObject const activity = QtAndroid::androidActivity(); if (activity.isValid()) { QAndroidJniObject const intent = activity.callObjectMethod("getIntent", "()Landroid/content/Intent;"); if (intent.isValid()) { QAndroidJniObject const data = intent.callObjectMethod("getData", "()Landroid/net/Uri;"); if (data.isValid()) { QAndroidJniObject const path = data.callObjectMethod("getPath", "()Ljava/lang/String;"); if (path.isValid()) { model()->addGeoDataFile(path.toString()); connect( model()->fileManager(), SIGNAL(centeredDocument(GeoDataLatLonBox)), this, SLOT(centerOn(GeoDataLatLonBox)) ); } } } } #endif }
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; }
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; }
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 }
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; }
QString getLocalPathFromUri(const QAndroidJniObject& uri) { // uri: Landroid/net/Uri; // [url](http://stackoverflow.com/questions/34163437/qt-and-android-gallery-mediastore-using-qandroidjniobject) QAndroidJniObject dadosAndroid = QAndroidJniObject::getStaticObjectField( "android/provider/MediaStore$MediaColumns", "DATA", "Ljava/lang/String;"); QAndroidJniEnvironment env; jobjectArray projecao = (jobjectArray)env->NewObjectArray(1, env->FindClass("java/lang/String"), NULL); jobject projacaoDadosAndroid = env->NewStringUTF(dadosAndroid.toString().toStdString().c_str()); env->SetObjectArrayElement(projecao, 0, projacaoDadosAndroid); QAndroidJniObject contentResolver = QtAndroid::androidActivity() .callObjectMethod("getContentResolver", "()Landroid/content/ContentResolver;"); QAndroidJniObject cursor = contentResolver.callObjectMethod("query", "(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;", uri.object<jobject>(), projecao, NULL, NULL, NULL); jint columnIndex = cursor.callMethod<jint>("getColumnIndex", "(Ljava/lang/String;)I", dadosAndroid.object<jstring>()); cursor.callMethod<jboolean>("moveToFirst", "()Z"); QAndroidJniObject resultado = cursor.callObjectMethod("getString", "(I)Ljava/lang/String;", columnIndex); QString imagemCaminho = "file://" + resultado.toString(); return imagemCaminho; }
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(); }
void NativeMap::handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject & data) { int LOCATE_EVENT_VENUE = 1; jint Activity__RESULT_OK = QAndroidJniObject::getStaticField<jint>( "android.app.Activity", "RESULT_OK"); if ( receiverRequestCode == LOCATE_EVENT_VENUE && resultCode == Activity__RESULT_OK ) { QAndroidJniObject addressName = QAndroidJniObject::fromString(QString("addressName")); QAndroidJniObject lat = QAndroidJniObject::fromString(QString("latitude")); QAndroidJniObject lon = QAndroidJniObject::fromString(QString("longitude")); QAndroidJniObject extras = data.callObjectMethod("getExtras","()Landroid/os/Bundle;"); qDebug() << __FUNCTION__ << "extras.isValid()=" << extras.isValid(); QAndroidJniObject addressNameObj = extras.callObjectMethod("getString","(Ljava/lang/String;)Ljava/lang/String;", addressName.object<jobject>()); qDebug() << __FUNCTION__ << "addressNameObj.isValid()=" << addressNameObj.isValid(); QAndroidJniObject latitudeObj = extras.callObjectMethod("getString","(Ljava/lang/String;)Ljava/lang/String;", lat.object<jobject>()); qDebug() << __FUNCTION__ << "latitudeObj.isValid()=" << latitudeObj.isValid(); QAndroidJniObject longitudeObj = extras.callObjectMethod("getString","(Ljava/lang/String;)Ljava/lang/String;", lon.object<jobject>()); qDebug() << __FUNCTION__ << "longitudeObj.isValid()=" << longitudeObj.isValid(); qDebug() << __FUNCTION__ << "address=" << addressNameObj.toString(); //this->setVenue(addressNameObj.toString()); emit this->locationSelected( longitudeObj.toString().toDouble(), latitudeObj.toString().toDouble(), addressNameObj.toString()); // double lond = (double)longitudeObj.callMethod<jdouble>("doubleValue", "()D"); // double latd = (double)latitudeObj.callMethod<jdouble>("doubleValue", "()D"); qDebug() << __FUNCTION__ << "latd.isValid()=" << latitudeObj.toString(); qDebug() << __FUNCTION__ << "lond.isValid()=" << longitudeObj.toString(); //this->setLatitude(latitudeObj.toString().toDouble()); //this->setLongitude(longitudeObj.toString().toDouble()); } }
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 }
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)); }
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); } } }
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); }
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; }
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()); }
bool ScreenValues::retrieveIsTablet() { #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 configuration = resources.callObjectMethod("getConfiguration", "()Landroid/content/res/Configuration;"); jint smallestScreenWidthDp = configuration.getField<jint>("smallestScreenWidthDp"); return smallestScreenWidthDp >= 600; #else return false; #endif }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QQmlApplicationEngine engine; QString mainQml = QStringLiteral(QML_DEVELOPMENT); qmlRegisterSingletonType<ScreenValues>("AzerothEarth", 1, 0, "ScreenValues", screen_values_provider); qmlRegisterSingletonType<ImageShare>("AzerothEarth", 1, 0, "ImageShare", image_share_provider); float dpi = QGuiApplication::primaryScreen()->physicalDotsPerInch(); /// TODO: Q_OS_BLACKBERRY || Q_OS_WINPHONE #ifdef Q_OS_IOS mainQml = QStringLiteral("qrc:/qml/main_ios.qml"); #elif 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;"); dpi = displayMetrics.getField<float>("density"); mainQml = QStringLiteral("qrc:/qml/main_android.qml"); #elif SIM QCursor cursor(QPixmap(":/qml/img/sim/cursor-default.png")); app.setOverrideCursor(cursor); mainQml = QStringLiteral("qrc:/qml/simfinger.qml"); #endif engine.rootContext()->setContextProperty("$", QVariant::fromValue(dpi)); engine.load(QUrl(mainQml)); return app.exec(); }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QtQuick2ApplicationViewer viewer; QVariantMap androidContext; androidContext["density"] = 1.0; #ifdef Q_OS_ANDROID QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); QAndroidJniObject resource = activity.callObjectMethod("getResources","()Landroid/content/res/Resources;"); QAndroidJniObject metrics = resource.callObjectMethod("getDisplayMetrics","()Landroid/util/DisplayMetrics;"); androidContext["density"] = metrics.getField<float>("density"); #endif viewer.setMainQmlFile(QStringLiteral("qml/androidmetricdemo/splash.qml")); viewer.showExpanded(); QQuickItem *root = viewer.rootObject(); QMetaObject::invokeMethod(root,"init",Qt::QueuedConnection, Q_ARG(QVariant,androidContext)); return app.exec(); }
void Wpp::downloadURL(const QString& url) { #ifdef Q_OS_ANDROID /* String serviceString = Context.DOWNLOAD_SERVICE; DownloadManager downloadManager; downloadManager = (DownloadManager)getSystemService(serviceString); Uri uri = Uri.parse("http://developer.android.com/shareables/icon_templates-v4.0.zip"); DownloadManager.Request request = new Request(uri); long reference = downloadManager.enqueue(request); */ QAndroidJniObject Context__DOWNLOAD_SERVICE = QAndroidJniObject::getStaticObjectField( "android/content/Context", "DOWNLOAD_SERVICE", "Ljava/lang/String;"); qDebug() << __FUNCTION__ << "Context__DOWNLOAD_SERVICE.isValid()=" << Context__DOWNLOAD_SERVICE.isValid(); QAndroidJniObject activity = QtAndroid::androidActivity(); qDebug() << __FUNCTION__ << "activity.isValid()=" << activity.isValid(); QAndroidJniObject downloadManager = activity.callObjectMethod( "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;", Context__DOWNLOAD_SERVICE.object<jstring>() ); qDebug() << __FUNCTION__ << "downloadManager.isValid()=" << downloadManager.isValid(); QAndroidJniObject urlJavaString = QAndroidJniObject::fromString(url); QAndroidJniObject uri = QAndroidJniObject::callStaticObjectMethod( "android/net/Uri", "parse", "(Ljava/lang/String;)Landroid/net/Uri;", urlJavaString.object<jstring>() ); qDebug() << __FUNCTION__ << "uri.isValid()=" << uri.isValid(); QAndroidJniObject request = QAndroidJniObject( "android/app/DownloadManager$Request","(Landroid/net/Uri;)V", uri.object<jobject>() ); qDebug() << __FUNCTION__ << "request.isValid()=" << request.isValid(); jlong reference = downloadManager.callMethod<jlong>( "enqueue","(Landroid/app/DownloadManager$Request;)J", request.object<jobject>()); qDebug() << "reference=" << reference; #endif }
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 }
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 androidShowBusyIcon() { if(b_androidBusyShown) return; qDebug() << "Showit"; // 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; } // Call the desired method QAndroidJniObject data = activity.callObjectMethod("showBusyCircle", "()Ljava/lang/String;"); b_androidBusyShown = true; }
double GetAndroidDisplaySize() { double ret = 200.; // sane default // 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; } // Call the desired method QAndroidJniObject data = activity.callObjectMethod("getDisplayDPI", "()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); } wxString istr = return_string.BeforeFirst('.'); long ldpi; if( istr.ToLong(&ldpi)){ ret = (::wxGetDisplaySize().x/(double)ldpi) * 25.4; } return ret; }
double GetAndroidDisplaySize() { double ret = 200.; // sane default // 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; } // 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); } wxLogMessage(_T("Metrics:") + return_string); wxSize screen_size = ::wxGetDisplaySize(); wxString msg; msg.Printf(_T("wxGetDisplaySize(): %d %d"), screen_size.x, screen_size.y); wxLogMessage(msg); double density = 1.0; wxStringTokenizer tk(return_string, _T(";")); if( tk.HasMoreTokens() ){ wxString token = tk.GetNextToken(); // xdpi token = tk.GetNextToken(); // density long b = ::wxGetDisplaySize().y; token.ToDouble( &density ); } double ldpi = 160. * density; double maxDim = wxMax(::wxGetDisplaySize().x, ::wxGetDisplaySize().y); ret = (maxDim / ldpi) * 25.4; msg.Printf(_T("Android Auto Display Size (mm, est.): %g"), ret); wxLogMessage(msg); // wxString istr = return_string.BeforeFirst('.'); // // long ldpi; // if( istr.ToLong(&ldpi)){ // ret = (::wxGetDisplaySize().x/(double)ldpi) * 25.4; // } return ret; }