Android實時獲得經緯度,傳送給c++服務端

Dsp Tian發表於2017-08-27

Android 客戶端:

複製程式碼
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 LocationManager locationManager;


    private final String SERVER_HOST_IP = "10.41.239.240";

    /* 伺服器埠 */
    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();

        // 獲取系統LocationManager服務
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // 從GPS獲取最近的定位資訊


        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        updateView(location);

        // 將location裡的位置資訊顯示在EditText中

        /* 設定每2秒獲取一次GPS的定位資訊 */

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1, new LocationListener() {

            @Override
            public void onLocationChanged(Location location) {
                // 當GPS定位資訊發生改變時,更新位置
                updateView(location);
            }

            @Override
            public void onProviderDisabled(String provider) {
                updateView(null);
            }

            @Override
            public void onProviderEnabled(String provider) {
                // 當GPS LocationProvider可用時,更新位置
                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(View v)
            {
          //      initClientSocket();
            }
        });

        btnSend.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage(show.getText().toString());
            }
        });

    }
    private void updateView(Location location) {
        if (location != null) {
            StringBuffer sb = new StringBuffer();
            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 {
            // 如果傳入的Location物件為空則隨便顯示點東西
            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
        {
      /* 連線伺服器 */
            socket = new Socket(SERVER_HOST_IP, SERVER_HOST_PORT);

      /* 獲取輸出流 */
            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新增:

<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" />

介面如下:

 

c++服務端:

複製程式碼
#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),&wsa)!=0)
    {
        printf("socket init error");
        exit(-1);
    }

    SOCKET serverSocket;

    if((serverSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET)
    {
        printf("建立套接字失敗!");
        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("link 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]='\0';
        printf("Message from %s:\n %s\n",inet_ntoa(clientAddress.sin_addr),buf);
    //    if(send(clientSocket,buf,bytes,0)==SOCKET_ERROR)
    //    {
    //        printf("傳送資料失敗!");
    ////        exit(-1);
    //    }

    }

    WSACleanup();
    exit(-1);

}
複製程式碼

相關文章