我如何发送的GPS和网络定位cordinates到服务器(静态IP)? [英] How can I send the GPS and Network location cordinates to a server (static IP)?

查看:375
本文介绍了我如何发送的GPS和网络定位cordinates到服务器(静态IP)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android Development.I初学者想打一个Android应用程序,它发送的GPS和网络位置(经纬度和放大器;长)到我的服务器(静态IP)。 我发现下面的code和它成功的工作,数据接收,在其已经在服务器端所做的应用程序(目前它无关,与客户端应用程序)

在我的服务器接收的数据,当我点击按钮发送位置在我的Andr​​oid应用程序。

  • GET /31.4244456/74.7349772 HTTP / 1.1

  • 主持人:180.178.169.77:6081

  • 连接:保持活动

  • 用户代理:Apache的HttpClient的/不可用(Java 1.4中)

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

在这一点上一切都很好,我来达到的,几乎是我想要的,但我现在面临的真正问题是,我的Andr​​oid应用程序挂起和崩溃发送该数据到服务器后。请解决我的问题,如果任何人有一个想法。

我已经找到了code从这里开始。 <一href="http://www.gideondsouza.com/blog/how-to-get-the-current-location-address-and-send-it-to-a-server-on-android#.UNLbTOT0Dxo" rel="nofollow">http://www.gideondsouza.com/blog/how-to-get-the-current-location-address-and-send-it-to-a-server-on-android#.UNLbTOT0Dxo

下面是我的AddressActivity.java

 包com.gideon.address;

进口java.io.IOException异常;
进口的java.util.List;
进口java.util.Locale中;

进口org.apache.http.Htt presponse;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.impl.client.DefaultHttpClient;
进口android.app.Activity;
进口android.content.Context;
进口android.location.Address;
进口android.location.Geo codeR;
进口android.location.Location;
进口android.location.LocationListener;
进口android.location.LocationManager;
进口android.os.Bundle;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.TextView;
进口android.widget.Toast;


公共类AddressActivity延伸活动{
/ **第一次创建活动时调用。 * /
字符串纬度=,LON =;

@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);

    按钮btnLocation =(按钮)findViewById(R.id.btnLocation);
    btnLocation.setOnClickListener(新OnClickListener(){
        公共无效的onClick(查看为arg0){
            //获取一个参考系统位置管理
            LocationManager locationManager =(LocationManager)AddressActivity.this.getSystemService(Context.LOCATION_SERVICE);
            //定义一个监听器,响应位置更新
            LocationListener的LocationListener的=新LocationListener的(){
                公共无效onLocationChanged(位置定位){
                    //当一个新的位置由网络位置提供商发现调用。
                    纬度= Double.toString(location.getLatitude());
                    经度= Double.toString(location.getLongitude());
                    TextView的电视=(TextView中)findViewById(R.id.txtLoc);
                    tv.setText(您现在的位置是:+纬度+ - + LON);
                }

                公共无效onStatusChanged(字符串商,INT地位,捆绑演员){}
                公共无效onProviderEnabled(字符串提供商){}
                公共无效onProviderDisabled(字符串提供商){}
            };
            //注册监听器的位置管理器来接收位置更新
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,LocationListener的);
        }
    });

    按钮btnSend =(按钮)findViewById(R.id.btnSend);
    btnSend.setOnClickListener(新OnClickListener(){
        公共无效的onClick(视图v){
            POSTDATA(纬度,经度);
        }
    });

    按钮btnAdd =(按钮)findViewById(R.id.btnAddress);
    btnAdd.setOnClickListener(新OnClickListener(){
        公共无效的onClick(视图v){
            TextView的电视=(TextView中)findViewById(R.id.txtAddress);
            tv.setText(的getAddress(纬度,经度));
        }
    });

}

公共无效POSTDATA(LA字符串,字符串LO){
    //创建一个新的HttpClient和门柱头球
    HttpClient的HttpClient的=新DefaultHttpClient();
    // HTTPGET htget =新HTTPGET(http://myappurl.com/Home/Book/+洛杉矶+/+ LO);
    HTTPGET htget =新HTTPGET(http://180.178.169.77:6081/+ LA +/+ LO);

    尝试 {
        //执行HTTP POST请求
        HTT presponse响应= httpclient.execute(htget);
        。字符串RESP = response.getStatusLine()的toString();
        Toast.makeText(这一点,RESP,5000).show();


    }赶上(ClientProtocolException E){
        Toast.makeText(这一点,错误,5000).show();
    }赶上(IOException异常E){
        Toast.makeText(这一点,错误,5000).show();
    }
}
公共字符串的getAddress(北纬字符串,字符串LON)
{
    地理codeR地理codeR =新的地缘codeR(这一点,Locale.ENGLISH);
    字符串RET =;
    尝试 {
        名单&LT;地址&gt;地址=地理coder.getFromLocation(Double.parseDouble(LAT),Double.parseDouble(LON),1);
        如果(地址!= NULL){
            地址returnedAddress = addresses.get(0);
            StringBuilder的strReturnedAddress =新的StringBuilder(地址:\ N);
            的for(int i = 0; I&LT; returnedAddress.getMaxAddressLineIndex();我++){
                strReturnedAddress.append(returnedAddress.getAddressLine(i))的追加(\ N)。
            }
            RET = strReturnedAddress.toString();
        }
        其他{
            RET =没有地址回来了!
        }
    }赶上(IOException异常E){
        // TODO自动生成的catch块
        e.printStackTrace();
        RET =无法获取地址!;
    }
    返回RET;
}
}
 

和这里是我的Andr​​oidManifest.xml

 &LT; XML版本=1.0编码=UTF-8&GT?;
&LT;舱单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    包=com.gideon.address
    安卓版code =1
    机器人:VERSIONNAME =1.0&GT;

    &LT;使用-SDK安卓的minSdkVersion =8/&GT;
    &LT;使用-权限的Andr​​oid:名称=android.permission.ACCESS_COARSE_LOCATION/&GT;
    &LT;使用-权限的Andr​​oid:名称=android.permission.INTERNET对/&GT;
    &lt;应用
        机器人:图标=@可绘制/ ic_launcher
        机器人:标签=@字符串/ APP_NAME&GT;
        &LT;活动
            机器人:名称=。AddressActivity
            机器人:标签=@字符串/ APP_NAME&GT;
            &LT;意向滤光器&gt;
                &lt;作用机器人:名称=android.intent.action.MAIN/&GT;

                &LT;类机器人:名称=android.intent.category.LAUNCHER/&GT;
            &所述; /意图滤光器&gt;
        &LT; /活性GT;
    &LT; /用途&gt;

&LT; /舱单&GT;
 

解决方案

移动 POSTDATA 关闭主线程辅助线程。看看异步任务的例子在这里:的 http://developer.android.com/reference/android/os/AsyncTask.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

这篇关于我如何发送的GPS和网络定位cordinates到服务器(静态IP)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆