Android real-time gain latitude and longitude, sent to the C + + service side

Source: Internet
Author: User
Tags gettext

Android Client:

Package Com.example.admin.gpsget;import Android. Manifest;import Android.content.context;import Android.content.pm.packagemanager;import android.location.Location ; Import Android.location.locationlistener;import Android.location.locationmanager;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.widget.edittext;import Android.widget.button;import Android.widget.toast;import Android.view.view;import Java.io.IOException;import Java.io.printstream;import Java.net.socket;import Java.net.unknownhostexception;import Java.util.Timer;import Java.util.timertask;import Android.os.asynctask;import Android.os.bundle;import Android.os.Handler;import Android.os.handlerthread;import android.os.message;import static Java.lang.thread.sleep;import Java.util.Timer; Import Java.util.timertask;public class Mainactivity extends appcompatactivity implements runnable{private Locationman    Ager Locationmanager;    Private final String server_host_ip = "10.41.239.240"; /* ServicesPort */private final int server_host_port = 9400;    Private Button Btnconnect;    Private Button btnsend;    Private EditText Show;    private socket socket;    Private PrintStream output;    private thread thread;    public void Toasttext (String message) {Toast.maketext (this, message, Toast.length_long). Show ();        } public void HandleException (Exception e, String prefix) {e.printstacktrace ();    Toasttext (prefix + e.tostring ());        } @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Initview ();        Get system Locationmanager Service Locationmanager = (Locationmanager) getsystemservice (Context.location_service);        Obtaining the nearest location information from the GPS position locator = locationmanager.getlastknownlocation (Locationmanager.gps_provider);        Updateview (location); Display location information in EditText */* Set GPS location information every 2 seconds */LocatioNmanager.requestlocationupdates (Locationmanager.gps_provider, 1, New Locationlistener () {@Override public void Onlocationchanged (locations location) {//When GPS location information is changed, update position Updateview (LO            cation);            } @Override public void onproviderdisabled (String provider) {Updateview (null); } @Override public void onproviderenabled (String provider) {//When GPS LOCATIONP            When Rovider is available, update location Updateview (locationmanager.getlastknownlocation (provider));                                        } @Override public void onstatuschanged (String provider, int status,        Bundle extras) {}});        Thread=new Thread (this);        Thread.Start (); Btnconnect.setonclicklistener (New Button.onclicklistener () {@Override public void OnClick (Vi      EW v) {//Initclientsocket ();        }        });                Btnsend.setonclicklistener (New Button.onclicklistener () {@Override public void OnClick (View v) {            SendMessage (Show.gettext (). toString ());    }        }); } private void Updateview {if (location = null) {StringBuffer SB = new Stringbu            Ffer ();            Sb.append ("Position: \nlat:");            Sb.append (Location.getlongitude ());            Sb.append ("\NLNG:");            Sb.append (Location.getlatitude ());            Sb.append ("\nhight:");            Sb.append (Location.getaltitude ());            Sb.append ("\nspeed:");            Sb.append (Location.getspeed ());            Sb.append ("\ndirection:");            Sb.append (Location.getbearing ());            Sb.append ("\njingdu:");            Sb.append (Location.getaccuracy ());            Sb.append ("\ n");        Show.settext (Sb.tostring ());      } else {//If the incoming location object is empty then show something casually      Show.settext ("JUYGFUGF");        }} public void Initview () {btnconnect = (Button) Findviewbyid (r.id.btnconnect);        Btnsend = (Button) Findviewbyid (r.id.btnsend);        Show = (EditText) Findviewbyid (R.id.edittext);        Btnsend.setenabled (FALSE);    Show.setenabled (FALSE);            } public void Closesocket () {try {output.close ();        Socket.close ();        } catch (IOException e) {handleexception (E, "close exception:"); }} private void Initclientsocket () {try {/* Connect server */socket = new Socket (Server_      HOST_IP, Server_host_port);            /* Get the output stream */output = new PrintStream (Socket.getoutputstream (), True, "utf-8");            Btnconnect.setenabled (FALSE);        Btnsend.setenabled (TRUE);         } catch (Unknownhostexception e) {handleexception (E, "Unknown host exception:" + e.tostring ()); } CATCH (IOException e) {handleexception (E, "IO exception:" + e.tostring ());    }} private void SendMessage (String msg) {output.print (msg);         } @Override public void Run () {initclientsocket ();            while (true) {try {thread.currentthread (). Sleep (5000);            } catch (Interruptedexception e) {e.printstacktrace ();        } sendMessage (Show.gettext (). toString ()); }    }}

Androidmanifest.xml Add:

<uses-permission android:name= "Android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name= "Android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name= "Android.permission.INTERNET"/>

The interface is as follows:

C + + Service side:

#include <WinSock2.h> #include <stdio.h> #include <Windows.h> #pragma comment (lib, "Ws2_32.lib") int    Main (int Argc,char *argv[]) {short port;    port=9400;    Wsadata WSA;        if (WSAStartup (Makeword (2,2), &AMP;WSA)!=0) {printf ("Socket init error");    Exit (-1);    } SOCKET ServerSocket; if ((Serversocket=socket (AF_INET,SOCK_STREAM,IPPROTO_TCP)) ==invalid_socket) {printf ("Create socket failed!        ");    Exit (-1);    } struct sockaddr_in serveraddress;    memset (&serveraddress,0,sizeof (sockaddr_in));    Serveraddress.sin_family=af_inet; Serveraddress.sin_addr. S_un.    S_addr=htonl (Inaddr_any);    Serveraddress.sin_port=htons (port); if (Bind (ServerSocket, (sockaddr*) &serveraddress,sizeof (serveraddress)) ==socket_error) {printf ("SOCKET Port        error:%d ", port);    Exit (-1);        } if (Listen (serversocket,somaxconn) ==socket_error) {printf ("Listen ERROR");    Exit (-1);   } printf ("Server 9400 is listening......\n"); SOCKET Clientsocket;    struct sockaddr_in clientaddress;    memset (&clientaddress,0,sizeof (clientaddress));    int addrlen=sizeof (clientaddress); if ((Clientsocket=accept (ServerSocket, (sockaddr*) &clientaddress,&addrlen)) (==invalid_socket) {printf ("Li        NK error ");    Exit (-1);    } Char buf[4096];    while (1) {int bytes=recv (clientsocket,buf,sizeof (BUF), 0);            /* IF ((Bytes=recv (clientsocket,buf,sizeof (BUF), 0) ==socket_error) {printf ("Data ERROR");        Exit (-1);        }*/buf[bytes]= ' + ';    printf ("Message from%s:\n%s\n", Inet_ntoa (CLIENTADDRESS.SIN_ADDR), buf); if (send (clientsocket,buf,bytes,0) ==socket_error)//{//printf ("Send data failed!")    ");    Exit (-1);    }} wsacleanup (); Exit (-1);}

Android real-time gain latitude and longitude, sent to the C + + service side

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.