QT on Android GPS signal acquisition

Source: Internet
Author: User

0. Write at the front

I participated in a post of An Xiaohui Warrior. Did a QT on Android for the GSP related experiments. For a rainy back. So record them.


1. Qt on Android GPS system flow


Figure 1. System flowchart

1 See, the system has two levels: one is QT-based UI. Provides a button (Qpushbutton) to start the GPS. and a text field (Qtextbrowser) that displays the GPS signal. The second is the activity-based GPS service, providing GPS start-up, GPS signal escalation and other services. Two levels of interaction and C + + and Java interaction are implemented through JNI.

The overall clue to the system is seen in the form of arrows: in the QT layer, the button is clicked. The slot function Startgps is triggered. The function calls the activity layer's method Calledbycpp, while the Calledbycpp method sends the message to the MES handle, the message type is Msg_str_gps_loc. Handle after receiving the message. Call function Startamap to start GPS positioning. When the GPS is started, the location's real-time information is advertised in the function onlocationchanged () function, which sends the location information to the MSG handle via a message with a message type of Msg_rpt_gsp_inf. Handle calls the native method reportgpsinfo to send the message to the QT layer.

2. Create Androidproject

Figure 2 Creating Project

Project is named Qtandroidgps and its path is E:\WORK\C++\QT. After project is created. The folder structure is as follows:

Figure 3. Project initial File

In the above self-generated folder, add the folder Android:


Figure 4. Add Directory after Android

The contents of Android include for example the following:


Figure 5. Directory of Android Content

As you can see, the folder structure is similar to the Android project generated by Eclipse, with less assets. Folders such as Bin,gen,res, and files such as project.properties.

This project can be used with Baidu and the German library to locate. Its associated jar packages are Baidulbs_android.jar and Android_location_v1.1.2.jar, respectively. Both packages are put into the e:\work\c++\qt\qtandroid\android\libs.

At the same time. After building the Projectqtandroidgps, QT will take the initiative to generate the folder itself under path e:\work\c++\qt\:

E:\work\c++\qt\build-qtandroidgps-android_for_armeabi_v7a_gcc_4_8_qt_5_4_0-debug, the folder includes the following files:


Figure 6. The project folder built after QT builds project

The Android-build folder includes the QT-built Androidproject, which is the complete androidproject:


Figure 7. The Androidproject folder generated after QT builds project

It can be found that the files contained in the projecte:\work\c++\qt\qtandroid\android\ that we created previously, in addition to Anroidmanifest.xml, are copied into the files containing both jar packages and Java files:

Build-qtandroidgps-android_for_armeabi_v7a_gcc_4_8_qt_5_4_0-debug.

3. List of project files

3.1 E:\work\c++\qt\qtandroidgps\android\androidmanifest.xml


......


Figure 8. Androidmanifest.xml

This file is like the 4 important points of the callout:

①-> the package path to the Java file in E:\work\c++\qt\qtandroidgps\android\src

②-> to put Baidu and gold pack up. Must increase Api-key

③-> the class name of the corresponding activity

④-> need to turn on GPS location-related permissions

3.2.1 E:\work\c++\qt\qtandroidgps\mainwindow.h

#ifndef mainwindow_h#define mainwindow_h#include <QMainWindow> #include <qpushbutton>namespace Ui {class MainWindow;} Class Mainwindow:public qmainwindow{    q_objectpublic:    explicit MainWindow (Qwidget *parent = 0);    ~mainwindow ();p rotected:    bool Event (qevent *e);p rivate:    ui::mainwindow *ui;    Qpushbutton *btn; Click Start gpsprivate Slots:    void Startgps ();//btn corresponding click Slot function}; #endif//Mainwindow_h
3.2.2e:\work\c++\qt\qtandroidgps\Mainwindow.cpp

#include "mainwindow.h" #include "ui_mainwindow.h" #include <QAndroidJniObject> #include "CustomEvent.h"    Mainwindow::mainwindow (Qwidget *parent): Qmainwindow (parent), UI (new Ui::mainwindow) {ui->setupui (this);    BTN = new Qpushbutton ("Start", this);    Btn->setgeometry (Qrect (10, 10, 100, 50)); Connect (BTN, SIGNAL (clicked ()), this, SLOT (Startgps ()));} Mainwindow::~mainwindow () {Delete UI;}    void Mainwindow::startgps () {//qandroidjniobject javaaction = qandroidjniobject::fromstring (URL); Qandroidjniobject::callstaticmethod<void> (/* Call Java method, please refer to QT's Help document */"Com/mtn/mes/gpsservice", "CA Lledbycpp "," () V ");} BOOL Mainwindow::event (qevent *e) {if (e->type () = = Customevent::eventtype ()) {/* matches on its own defined event type */E->accept (        );       Customevent *sce = (customevent*) e;        _resultview->settext (SCE-&GT;M_ARG2); Ui->textbrowser->settext (SCE-&GT;M_ARG2);    /* Display GPS information */return true; } return Qwidget::evENT (e);} 

3.3.1e:\work\c++\qt\qtandroidgps\CustomEvent.h

#ifndef customevent_h#define customevent_h#include <QEvent> #include <qstring>class customevent:public Qevent{public:    customevent (int arg1 = 0, const QString &ARG2 = QString ());    ~customevent ();    Static Type EventType ();    int m_arg1;    QString m_arg2;private:    static Type m_evtype;}; #endif//Customevent_h
3.3.2e:\work\c++\qt\qtandroidgps\CustomEvent.cpp

#include "CustomEvent.h" qevent::type Customevent::m_evtype = (qevent::type) qevent::none; customevent::customevent (int arg1, const QString &arg2)    : Qevent (EventType ()), M_arg1 (arg1), M_arg2 (arg2) {} Customevent::~customevent () {}qevent::type customevent::eventtype () {    if (M_evtype = = Qevent::none)    {        m_ Evtype = (qevent::type) registereventtype (); /* Register yourself to define the event, return the M_evtype value to the QT assigned self-defined event type */    }    return m_evtype;}
3.4e:\work\c++\qt\qtandroidgps\CustomEvent.cpp
#include "mainwindow.h" #include <QApplication> #include <QDebug> #include <jni.h> #include < qandroidjnienvironment> #include <QAndroidJniObject> #include "CustomEvent.h" qobject *main_window = 0;/*    This function is called by the Java Local method */static void Reportgpsinfo (jnienv *env, jobject thiz,int result, jstring data) {QString qstrdata;    const char *nativestring = env->getstringutfchars (data, 0);    Qstrdata = nativestring;    Env->releasestringutfchars (data, nativestring); Qcoreapplication::p ostevent (Main_window, new customevent (result, qstrdata)); /* Send events (carry GPS information) to the main form. Define your own event type */Qdebug () << qstrdata;} BOOL Registernativemethods () {Jninativemethod methods[] {{"Reportgpsinfo", "(iljava/lang/string;) V", (void*) Rep    Ortgpsinfo}/* Register local method, Java can invoke, specific information see QT Help document */};    const char *classname = "com/mtn/mes/extendsqtnative";    Jclass Clazz;    Qandroidjnienvironment env;    Qandroidjniobject Javaclass (classname); Clazz = Env->getobjectclass (javaclass.oBject<jobject> ());    Qdebug () << "Find Extendsqtnative-" << 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;}    int main (int argc, char *argv[]) {qapplication A (argc, argv);    MainWindow W; Customevent::eventtype ();  Register yourself to define events, generate your own definition of event type registernativemethods ();    Register Local method W.show ();    Main_window = qobject_cast<qobject*> (&w); return a.exec ();}
3.5E:\work\c++\qt\qtandroidgps\android\src\com\mtn\mes\extendsqtnative.java

Package Com.mtn.mes;import Java.lang.string;public class extendsqtnative{public    native void Reportgpsinfo (int result, String content);}
3.6e:\work\c++\qt\qtandroidgps\android\src\com\mtn\mes\Gpsservice.java

Package Com.mtn.mes;import Java.lang.string;import Android.content.context;import android.content.intent;import Android.app.pendingintent;import Android.os.handler;import Android.os.message;import Android.util.Log;import Android.net.connectivitymanager;import Android.net.networkinfo;import Android.net.uri;import Android.location.criteria;import Android.provider.settings;import Android.os.bundle;import android.os.Environment ; Import Java.io.file;import Com.loopj.android.http.asynchttpclient;import Com.loopj.android.http.asynchttpresponsehandler;import Android.widget.toast;import Java.util.Date;import Android.location.location;import Android.location.locationlistener;import Android.location.LocationManager; Import Com.amap.api.location.amaplocation;import Com.amap.api.location.amaplocationlistener;import Com.amap.api.location.locationmanagerproxy;import Com.amap.api.location.locationproviderproxy;import Com.baidu.location.bdlocation;import Com.baidu.location.bdlocationlistener;import Com.bAidu.location.locationclient;import Com.baidu.location.locationclientoption;import Com.baidu.location.locationclientoption.locationmode;public class Gpsservice extends    org.qtproject.qt5.android.bindings.qtactivity{private static Gpsservice m_instance;    Private final static String TAG = "Gpsservice";    Private final static int msg_str_gps_loc = 0;    Private final static int msg_rpt_gps_inf = 1; Locating related////////////////////    Private Locationmanagerproxy Amapmanager;    Public Gpsservice () {m_instance = this;        } public static void Calledbycpp () {System.out.println ("[0]hello world!");        Message msg = new Message ();        Msg.what = Msg_str_gps_loc; M_instance.handler.sendMessage (msg); Message trigger, start GPS positioning//m_instance.handler.sendemptymessage (0); Message is triggered. Start GPS location} public static void Calledbycpp (int arG0) {System.out.println ("[1]hello world!");        private void Startamap () {Amapmanager = Locationmanagerproxy.getinstance (this);         /* * Mamaplocmanager.setgpsenable (FALSE); * 1.0.2 version number new method, set true to indicate that the hybrid location includes GPS positioning, false for pure network location, the default is true location * API positioning using GPS and Network hybrid positioning method *, the first parameter is positioning provide R, the second parameter is the shortest 2000 milliseconds, the third parameter distance interval is the meter, the fourth parameter is the location listener/amapmanager.requestlocationupdates (locationproviderproxy.am    Apnetwork, Mamaplocationlistener);  } private Amaplocationlistener Mamaplocationlistener = new Amaplocationlistener () {@Override public void Onstatuschanged (String provider, int status, Bundle extras) {} @Override public void Onproviderenab        LED (string provider) {} @Override public void onproviderdisabled (string provider) {} @Override public void Onlocationchanged {} @Override public void Onlocatio NchangEd (amaplocation location) {if (location! = null) {Double Geolat = Location.getlatitude ();                Double geolng = Location.getlongitude ();                String Citycode = "";                String desc = "";                Bundle Locbundle = Location.getextras ();                    if (locbundle! = null) {Citycode = locbundle.getstring ("Citycode");                desc = locbundle.getstring ("desc");   } String str = ("Location OK: (" + geolng + "," + Geolat + ")" + "\naccuracy : "+ location.getaccuracy () +" Meter "+" \npositioning: "+ location.getprovider () +" \nposi                Tioning time: "+ New Date (Location.gettime ()). toLocaleString () +" \ncity coding: "+ Citycode + "\nlocation Description:" + desc + "\nprovince:" + location.getprovince () + "\ncity:" + Location.getcity () + "\ nDistrict (county): "+ location.getdistrict () +" \nregional Coding: "+ location.getadcode ());                Toast.maketext (Getapplicationcontext (), "German position \ n" + str, toast.length_short). Show ();                Send location information to handler, hander to QT message msg = new Message ();                Bundle data = new bundle ();                Data.putstring ("value", str);                Msg.setdata (data);                Msg.what = Msg_rpt_gps_inf;            Handler.sendmessage (msg);    }        }    }; Private Handler Handler = new Handler () {@Override public void Handlemessage (Message msg) {Swit               CH (msg.what) {case MSG_STR_GPS_LOC://Message type is start GPS positioning m_instance.startamap ();               Break                   Case Msg_rpt_gps_inf://Message type is on send GSP information extendsqtnative m_nativenotify = new Extendsqtnative ();                   Bundle data = Msg.getdata (); System.out.println(Data.getstring ("value")); M_nativenotify.reportgpsinfo (0, data.getstring ("value"));               Drop the C + + method break;               Default:System.out.println ("msg type error!");            Break }        }    };}

Click to download source code

QT on Android GPS signal acquisition

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.