2012-12-30 37 views
2

我是Android开发的初学者。我想制作一个android应用程序,将GPS和网络位置(经纬度为&长)发送到我的服务器(静态IP)。 我发现下面的代码,它的工作成功,数据接收已在服务器端的应用程序(现在它与客户端应用程序无关)如何将GPS和网络位置坐标发送给服务器(静态IP)?

当我点击按钮时在我的服务器上收到的数据'在我的Android应用上发送位置'。

  • GET /31.4244456/74.7349772 HTTP/1.1

  • 主持人:180.178.169.77:6081

  • 连接:保持活跃

  • 的User-Agent:Apache的HttpClient的/不可用(java 1.4)

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

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

我从这里找到了该代码。 http://www.gideondsouza.com/blog/how-to-get-the-current-location-address-and-send-it-to-a-server-on-android#.UNLbTOT0Dxo

这里是我的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; 
} 
} 

这里是我的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> 

回答

0

您的问题是

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

在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 
    } 
} 
+0

谢谢你,让我试试这个,然后我会让你知道,如果工程:) – user2010282

+0

能否请您指导我,我应该从我的代码删除,哪儿我应该添加上面的代码到我的Addressactivity.java?因为当我在上面的代码添加到我的主要的应用程序代码,它给了我很多帮助errors.please me.Thanks – user2010282

+0

某处添加PostAsyncTask类AddressActivity类的内部和替换btnSend OnClickListener的onClick(视图v)用的onClick(视图V)我张贴。我强烈建议您按照Slartibartfast的建议阅读Android AsyncTask文档。 –

0

该问题的解决方案是:

增加了一个新的线程

       new Thread(new Runnable() { 
        public void run() { 
         // your code goes here 
         postData(lat, lon); 
         } 

        }).start(); 

     } 

和代码如下:

  Button btnSend = (Button)findViewById(R.id.btnSend); 
    btnSend.setOnClickListener(new OnClickListener() { 
      public void onClick(View v) { 
       new Thread(new Runnable() { 
        public void run() { 
         // your code goes here 
         postData(lat, lon); 
         } 

        }).start(); 

     } 

    }); 

和我的完整代码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.client.methods.HttpPost; 
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) { 
       new Thread(new Runnable() { 
        public void run() { 
         // your code goes here 
         postData(lat, lon); 
         } 

        }).start(); 

     } 

    }); 

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

    HttpPost httppost = new HttpPost("http://180.178.169.77:6081/"+la+"/"+lo); 


    try { 

     // Execute HTTP Post Request 
     //HttpResponse response = httpclient.execute(htget); 
     HttpResponse response = httpclient.execute(httppost); 
     //String resp = response.getStatusLine().toStrinkatyg(); try this now 
     //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; 
//} 
} 

我不知道,吨需要地址,geolocations功能,所以我评论有关它的一切。 那是我在Android应用程序第一个工作日,如果我错了地方请指导我,告诉我我该如何提高它。

也请帮助我,如果:

1)我想删除发送位置按钮,这样我的位置会自动进入到我的服务器定期对定义的时间间隔说10分钟。

而第二件事:

2)我想我的应用程序选择最好的供应商,GPS或GSM网络中,如果没有可用发送邮件使用其他的位置。

相关问题