我怎样才能将GPS和网络位置坐标发送到一个服务器(静态IP)?[英] How can I send the GPS and Network location cordinates to a server (static IP)?

本文是小编为大家收集整理的关于我怎样才能将GPS和网络位置坐标发送到一个服务器(静态IP)?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我是Android开发的初学者.我想制作一个Android应用程序,该应用将GPS和网络位置(LAT&LONG)发送到我的服务器(静态IP). 我找到了以下代码,并且成功地工作了,在服务器端已经制作的应用程序接收到(现在它与客户端应用无关)

)

当我单击Android应用程序上的"发送位置"时,在我的服务器上收到的数据.

  • get/31.4244456/74.7349772 http/1.1

  • 主机:180.178.169.77:6081

  • 连接:keep-alive

  • 用户代理:apache-httpclient/nocabairable(Java 1.4)

180.178.169.77是我的服务器IP,6081是端口

在这一点上一切都很好,我几乎可以实现我想要的东西,但是我面临的真正问题是我的Android应用程序在将这些数据发送到服务器后会挂起并崩溃.如果有人有想法,请解决我的问题.

我从这里找到了代码. http://www.gideondsouza.com/blog/how-to-get-the-current-location-location-location-location-location-location-locat--and-send-send-in-t-to-to-to-a-server-in-server-on-on-onlbtot.unlbtot0dxo

这是我的地址activity.java

package com.gideon.address;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class AddressActivity extends Activity {
/** Called when the activity is first created. */
String lat="", lon="";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button btnLocation = (Button)findViewById(R.id.btnLocation);
    btnLocation.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            // Acquire a reference to the system Location Manager
            LocationManager locationManager = (LocationManager) AddressActivity.this.getSystemService(Context.LOCATION_SERVICE);
            // Define a listener that responds to location updates
            LocationListener locationListener = new LocationListener() {
                public void onLocationChanged(Location location) {
                    // Called when a new location is found by the network location provider.
                    lat = Double.toString(location.getLatitude());
                    lon = Double.toString(location.getLongitude());
                    TextView tv = (TextView) findViewById(R.id.txtLoc);
                    tv.setText("Your Location is:" + lat + "--" + lon);
                }

                public void onStatusChanged(String provider, int status, Bundle extras) {}
                public void onProviderEnabled(String provider) {}
                public void onProviderDisabled(String provider) {}
            };
            // Register the listener with the Location Manager to receive location updates
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
        }
    });

    Button btnSend = (Button)findViewById(R.id.btnSend);
    btnSend.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            postData(lat, lon);
        }
    });

    Button btnAdd = (Button)findViewById(R.id.btnAddress);
    btnAdd.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            TextView tv = (TextView)findViewById(R.id.txtAddress);
            tv.setText(GetAddress(lat, lon));
        }
    });

}

public void postData(String la, String lo) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    //HttpGet  htget = new HttpGet("http://myappurl.com/Home/Book/"+la+"/"+lo);
    HttpGet  htget = new HttpGet("http://180.178.169.77:6081/"+la+"/"+lo);

    try {
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(htget);
        String resp = response.getStatusLine().toString();
        Toast.makeText(this, resp, 5000).show();


    } catch (ClientProtocolException e) {
        Toast.makeText(this, "Error", 5000).show();
    } catch (IOException e) {
        Toast.makeText(this, "Error", 5000).show();
    }
} 
public String GetAddress(String lat, String lon)
{
    Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
    String ret = "";
    try {
        List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(lat), Double.parseDouble(lon), 1);
        if(addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
            for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
            }
            ret = strReturnedAddress.toString();
        }
        else{
            ret = "No Address returned!";
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        ret = "Can't get Address!";
    }
    return ret;
}
}

这是我的androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gideon.address"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AddressActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

推荐答案

将主线程移动到辅助线程.在此处查看Async任务以获取示例: http://developer.android.com.android.com/reference/android/os/asynctask.html

其他推荐答案

您的问题是

 public void onClick(View v) {
            postData(lat, lon);
        }

在UI线程上运行.这意味着,当您执行"邮政"操作时,UI不会刷新并且无法访问 - 您的应用程序会粘住,直到帖子结束.

您需要做类似:

的事情
  public void onClick(View v) {
        PostAsyncTask postAsyncTask = new PostAsyncTask();
        postAsyncTask.execute();
    }



 private class PostAsyncTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     postData(lat, lon);
     return 0;
 }

 protected void onPreExecute() {
     // show progress dialog
 }


     protected void onPostExecute(Long result) {
         // hide  progress dialog
     }
 }

本文地址:https://www.itbaoku.cn/post/102606.html

问题描述

I am a beginner in the Android Development.I want to make an android app which sends the GPS and network locations (lat & long) to my server (static IP). I have found the following code and it worked successfully, data receive at the app which is already made at server side (Right now it has nothing to do with client app)

Data received at my Server when I click the button 'Send Location' on my Android App.

  • GET /31.4244456/74.7349772 HTTP/1.1

  • Host: 180.178.169.77:6081

  • Connection: keep-Alive

  • User-Agent: Apache-HttpClient/Unavailable (java 1.4)

180.178.169.77 is my server IP and 6081 is the port

At this point everything is going fine and I acheived almost what I wanted but the real problem I'm facing is that my Android app hangs and crash after sending this data to server. Please resolve my problem if anybody has an idea.

I have found the Code from here. http://www.gideondsouza.com/blog/how-to-get-the-current-location-address-and-send-it-to-a-server-on-android#.UNLbTOT0Dxo

Here is my AddressActivity.java

package com.gideon.address;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class AddressActivity extends Activity {
/** Called when the activity is first created. */
String lat="", lon="";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button btnLocation = (Button)findViewById(R.id.btnLocation);
    btnLocation.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            // Acquire a reference to the system Location Manager
            LocationManager locationManager = (LocationManager) AddressActivity.this.getSystemService(Context.LOCATION_SERVICE);
            // Define a listener that responds to location updates
            LocationListener locationListener = new LocationListener() {
                public void onLocationChanged(Location location) {
                    // Called when a new location is found by the network location provider.
                    lat = Double.toString(location.getLatitude());
                    lon = Double.toString(location.getLongitude());
                    TextView tv = (TextView) findViewById(R.id.txtLoc);
                    tv.setText("Your Location is:" + lat + "--" + lon);
                }

                public void onStatusChanged(String provider, int status, Bundle extras) {}
                public void onProviderEnabled(String provider) {}
                public void onProviderDisabled(String provider) {}
            };
            // Register the listener with the Location Manager to receive location updates
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
        }
    });

    Button btnSend = (Button)findViewById(R.id.btnSend);
    btnSend.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            postData(lat, lon);
        }
    });

    Button btnAdd = (Button)findViewById(R.id.btnAddress);
    btnAdd.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            TextView tv = (TextView)findViewById(R.id.txtAddress);
            tv.setText(GetAddress(lat, lon));
        }
    });

}

public void postData(String la, String lo) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    //HttpGet  htget = new HttpGet("http://myappurl.com/Home/Book/"+la+"/"+lo);
    HttpGet  htget = new HttpGet("http://180.178.169.77:6081/"+la+"/"+lo);

    try {
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(htget);
        String resp = response.getStatusLine().toString();
        Toast.makeText(this, resp, 5000).show();


    } catch (ClientProtocolException e) {
        Toast.makeText(this, "Error", 5000).show();
    } catch (IOException e) {
        Toast.makeText(this, "Error", 5000).show();
    }
} 
public String GetAddress(String lat, String lon)
{
    Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
    String ret = "";
    try {
        List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(lat), Double.parseDouble(lon), 1);
        if(addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
            for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
            }
            ret = strReturnedAddress.toString();
        }
        else{
            ret = "No Address returned!";
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        ret = "Can't get Address!";
    }
    return ret;
}
}

And here is my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gideon.address"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AddressActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

推荐答案

Move postData off the main thread to a secondary thread. Look at Async task for examples here: http://developer.android.com/reference/android/os/AsyncTask.html

其他推荐答案

Your problem is that

 public void onClick(View v) {
            postData(lat, lon);
        }

runs on the UI thread. It means that while you do the "post" action, the UI isn't refreshed and cannot be accessed - your app get stuck until the post ends.

You need to do something like:

  public void onClick(View v) {
        PostAsyncTask postAsyncTask = new PostAsyncTask();
        postAsyncTask.execute();
    }



 private class PostAsyncTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     postData(lat, lon);
     return 0;
 }

 protected void onPreExecute() {
     // show progress dialog
 }


     protected void onPostExecute(Long result) {
         // hide  progress dialog
     }
 }