Android实时获得经纬度,发送给c++服务端

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);

}
复制代码

posted @ 2017-08-27 15:28 Dsp Tian 阅读(...) 评论(...) 编辑 收藏