如何发送位置服务器? [英] how to send location to server?
本文介绍了如何发送位置服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用列表视图在我的Android应用我想当前位置发送用户到服务器。为了这个,我用下面的code ........
公共类家庭扩展ListActivity { 私人ProgressDialog pDialog; // URL获得接触JSON
私有静态字符串URL =http://api-11hr.anovatesoft.com/v1/list; // JSON节点名称
私有静态最后弦乐TAG_CONTACTS =接触;
私有静态最后弦乐TAG_USERNAME =用户名;
私有静态最后弦乐TAG_NAME =名;
私有静态最后弦乐TAG_EMAIL =电子邮件;
私有静态最后弦乐TAG_ADDRESS =地址;
私有静态最后弦乐TAG_CONTACT_NUMBER =contactnumber;
私有静态最后弦乐TAG_POSTAL_ code =邮政code;
是SessionManager会议;
私人字符串apikey;
GPSTracker GPS;
//接触JSONArray
JSONArray接触= NULL; //为哈希映射的ListView
ArrayList的<&HashMap的LT;字符串,字符串>>联系人列表; @覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.home);
Gps_func();
//会话类实例
会话=新SessionManager(中间getApplicationContext()); //从会话用户数据
HashMap的<字符串,字符串>用户= session.getUserDetails();
// apikey
//调用的应用程序类(请参阅在AndroidManifest.xml应用标签)
最终GlobalClass globalVariable =(GlobalClass)getApplicationContext(); //设置的姓名和电子邮件全球/应用程序上下文
apikey = globalVariable.getApikey();
Log.v(楚,apikey); contactList =新的ArrayList<&HashMap的LT;字符串,字符串>>(); ListView控件LV = getListView(); //列表视图对项目点击监听器
lv.setOnItemClickListener(新OnItemClickListener(){ @覆盖
公共无效onItemClick(适配器视图<>母公司,观景,
INT位置,长的id){
//从选定的ListItem得到的值 串成本=((的TextView)view.findViewById(R.id.email))
.getText()的toString()。
//开始单触点活动
在意向=新意图(getApplicationContext()
Adds.class); in.putExtra(TAG_EMAIL,成本); startActivity(在); }
}); //调用异步任务来获得JSON
新GetContacts()执行();
} 私人无效Gps_func(){ GPS =新GPSTracker(Home.this); //检查是否启用GPS
如果(gps.canGetLocation()){ 双纬度= gps.getLatitude();
双经度= gps.getLongitude(); // \\ n是新行
// Toast.makeText(getApplicationContext(),您现在的位置是 - \\ nLat:+纬度+\\ nLong:+经度,Toast.LENGTH_LONG).show();
Log.d(标签,经度:\\ n+经度+\\ n纬度:\\ n+纬度); }其他{
//无法获取位置
未启用// GPS或网络
//要求用户在设置中启用GPS /网络
gps.showSettingsAlert(); 如果(gps.canGetLocation()){
双纬度= gps.getLatitude();
双经度= gps.getLongitude(); // \\ n是新行
// Toast.makeText(getApplicationContext(),您现在的位置是 - \\ nLat:+纬度+\\ nLong:+经度,Toast.LENGTH_LONG).show();
Log.d(标签,经度:\\ n+经度+\\ n纬度:\\ n+纬度); }
}
GPSTracker currentLocation = NULL;
字符串纬度=新的String(+(Math.round(currentLocation.getLatitude()* 10000000))/ 10000000);
字符串的经度=新的String(+(Math.round(currentLocation.getLatitude()* 10000000))/ 10000000); //为了与服务器进行交互创建一个HTTP客户端和HTTP POST对象
HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httppost =新HttpPost(http://api-11hr.anovatesoft.com/v1/list);
尝试{ //创建标识符和值对,我们要发送到服务器的信息
清单<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;(2);
nameValuePairs.add(新BasicNameValuePair(LLT,纬度));
nameValuePairs.add(新BasicNameValuePair(长,经度)); //通过HTTP客户端将数据发送到服务器
httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
httpclient.execute(httppost);
}赶上(IOException异常五){
// TODO自动生成catch块
}
} @覆盖
保护无效onRestart(){
super.onRestart();
Gps_func();
}
/ **
*异步任务类,通过HTTP调用获得JSON
* * /
私有类GetContacts扩展的AsyncTask<太虚,太虚,太虚> { @覆盖
在preExecute保护无效(){
super.on preExecute();
//显示进度对话框
pDialog =新ProgressDialog(Home.this);
pDialog.setMessage(请稍候...);
pDialog.setCancelable(假);
pDialog.show(); } @覆盖
保护无效doInBackground(虚空......为arg0){
//创建服务处理程序类实例
ServiceHandler1 SH =新ServiceHandler1(apikey); //制作到URL的请求和响应得到
字符串jsonStr = sh.makeServiceCall(URL,ServiceHandler1.POST); Log.d(回应:,>中+ jsonStr); 如果(jsonStr!= NULL){
尝试{
JSONObject的jsonObj =新的JSONObject(jsonStr); //获取JSON数组节点
接触= jsonObj.getJSONArray(TAG_CONTACTS); //通过所有联系人循环
的for(int i = 0; I< contacts.length();我++){
JSONObject的C = contacts.getJSONObject(I) 字符串username = c.getString(TAG_USERNAME);
字符串名称= c.getString(TAG_NAME);
字符串email = c.getString(TAG_EMAIL);
字符串的地址= c.getString(TAG_ADDRESS);
字符串性别= c.getString(TAG_CONTACT_NUMBER);
字符串邮政code = c.getString(TAG_POSTAL_ code); // TMP的HashMap的单触点
HashMap的<字符串,字符串>接触=新的HashMap<字符串,字符串>(); //将每个子节点的HashMap键=>值 contact.put(TAG_EMAIL,电子邮件);
//添加联系人到联系人列表
contactList.add(接触);
}
}赶上(JSONException E){
e.printStackTrace();
}
}其他{
Log.e(的ServiceHandler,无法从URL得到任何数据);
} 返回null;
} @覆盖
保护无效onPostExecute(虚空结果){
super.onPostExecute(结果);
//辞退进度对话框
如果(pDialog.isShowing())
pDialog.dismiss();
/ **
*更新解析JSON数据到ListView控件
* * /
ListAdapter适配器=新SimpleAdapter(
Home.this,contactList,
R.layout.list_item1,新的String [] {TAG_EMAIL,
},新的INT [] {
R.id.email,}); setListAdapter(适配器);
} }}
本code我得到了的USR当前位置在我的日志,但无法将其解析到服务器.........
公共类GPSTracker扩展服务实现LocationListener的{ 私人最终上下文mContext; //标志GPS状态
布尔isGPSEnabled = FALSE; //标志网络状态
布尔isNetworkEnabled = FALSE; //标志GPS状态
布尔canGetLocation = FALSE; 地点位置; // 位置
双纬度; //纬度
双经度; //经度 //最小距离改变米的更新
私有静态最后长MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10米 //毫秒更新之间的最短时间
私有静态最后长MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1分钟 //声明一个位置管理
受保护的LocationManager的LocationManager; 公共GPSTracker(上下文的背景下){
this.mContext =背景;
的getLocation();
} 公共场所的getLocation(){
尝试{
的LocationManager =(的LocationManager)mContext
.getSystemService(LOCATION_SERVICE); //获取GPS状态
isGPSEnabled =的LocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER); //获取网络状态
isNetworkEnabled =的LocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 如果(isGPSEnabled&安培;!&安培;!isNetworkEnabled){
//没有启用网络供应商
}其他{
this.canGetLocation = TRUE;
如果(isNetworkEnabled){
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
Log.d(网络,网络);
如果(的LocationManager!= NULL){
位置=的LocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
如果(位置!= NULL){
纬度= location.getLatitude();
经度= location.getLongitude();
}
}
}
//如果GPS功能的获得纬度/长期使用GPS服务
如果(isGPSEnabled){
如果(位置== NULL){
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
Log.d(GPS已启用,GPS功能的);
如果(的LocationManager!= NULL){
位置=的LocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
如果(位置!= NULL){
纬度= location.getLatitude();
经度= location.getLongitude();
}
}
}
}
} }赶上(例外五){
e.printStackTrace();
} 返回的位置;
} / **
*停止使用GPS监听器
*调用此函数将停止在你的应用程序中使用GPS
* * /
公共无效stopUsingGPS(){
如果(的LocationManager!= NULL){
locationManager.removeUpdates(GPSTracker.this);
}
} / **
*函数来获取纬度
* * /
公共双getLatitude(){
如果(位置!= NULL){
纬度= location.getLatitude();
} //返回纬度
返回纬度;
} / **
*函数来获取经度
* * /
公共双getLongitude(){
如果(位置!= NULL){
经度= location.getLongitude();
} //返回经度
返回经度;
} / **
*功能检查启用GPS / WIFI
* @返回布尔
* * /
公共布尔canGetLocation(){
返回this.canGetLocation;
} / **
*功能,以显示设置警告对话框
*在pressing设置按钮将劳克设置选项
* * /
公共无效showSettingsAlert(){
AlertDialog.Builder alertDialog =新AlertDialog.Builder(mContext); //设置对话框标题
alertDialog.setTitle(GPS是设置); //设置对话框留言
alertDialog.setMessage(GPS未启用你想要去设置菜单?); //在pressing设置按钮
alertDialog.setPositiveButton(设置,新DialogInterface.OnClickListener(){
公共无效的onClick(DialogInterface对话,诠释它){
意向意图=新意图(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(意向);
}
}); //在pressing取消按钮
alertDialog.setNegativeButton(取消,新DialogInterface.OnClickListener(){
公共无效的onClick(DialogInterface对话,诠释它){
dialog.cancel();
AlertDialog.Builder alertDialog =新AlertDialog.Builder(mContext); //设置对话框标题
alertDialog.setTitle(关闭11小时); //设置对话框留言
alertDialog.setMessage(11小时被关闭,因为没有启用GPS!); //在pressing设置按钮
alertDialog.setPositiveButton(关闭程序,新DialogInterface.OnClickListener(){
公共无效的onClick(DialogInterface对话,诠释它){
System.exit(0); }
});
//显示警报信息
alertDialog.show();
}
}); //显示警报信息
alertDialog.show();
} @覆盖
公共无效onLocationChanged(地点){
} @覆盖
公共无效onProviderDisabled(字符串提供商){
} @覆盖
公共无效onProviderEnabled(字符串提供商){
} @覆盖
公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
} @覆盖
公众的IBinder onBind(意向为arg0){
返回null;
}}所以plz帮助我的人........
解决方案
一个简单的方法将数据发送到服务器是使用谷歌凌空库。 http://developer.android.com/intl/zh-cn /training/volley/index.html
i used list view in my android app i wants send the users current position to the server. for this i used the following code........
public class Home extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api-11hr.anovatesoft.com/v1/list";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_USERNAME = "username";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_CONTACT_NUMBER = "contactnumber";
private static final String TAG_POSTAL_CODE = "postalcode";
SessionManager session;
private String apikey;
GPSTracker gps;
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Gps_func();
// Session class instance
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// apikey
// Calling Application class (see application tag in AndroidManifest.xml)
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
//Set name and email in global/application context
apikey=globalVariable.getApikey();
Log.v("Chu Chu", apikey);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
Adds.class);
in.putExtra(TAG_EMAIL, cost);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Gps_func() {
gps = new GPSTracker(Home.this);
// check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
Log.d("tag", "Longitude:\n" + longitude + "\n Latitude: \n" + latitude);
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
Log.d("tag", "Longitude:\n" + longitude + "\n Latitude: \n" + latitude);
}
}
GPSTracker currentLocation = null;
String latitude = new String(" " + (Math.round(currentLocation.getLatitude()*10000000))/10000000);
String longitude = new String(" " + (Math.round(currentLocation.getLatitude()*10000000))/10000000);
// Creating an http client and http post object in order to interact with server
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://api-11hr.anovatesoft.com/v1/list");
try {
//Creating identifier and value pairs for the information we want to send to server
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Llt", latitude));
nameValuePairs.add(new BasicNameValuePair("long", longitude));
//Sending data to server via http client
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
@Override
protected void onRestart() {
super.onRestart();
Gps_func();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Home.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler1 sh = new ServiceHandler1(apikey);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler1.POST);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String username = c.getString(TAG_USERNAME);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_CONTACT_NUMBER);
String postalcode = c.getString(TAG_POSTAL_CODE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_EMAIL, email);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Home.this, contactList,
R.layout.list_item1, new String[] { TAG_EMAIL,
}, new int[] {
R.id.email, });
setListAdapter(adapter);
}
}
}
by this code i got the usrs current position on my log but unable to parse it to the server.........
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is setting");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("Close 11 Hour");
// Setting Dialog Message
alertDialog.setMessage("11 Hour is shutting down since GPS is not enabled!");
// On pressing Settings button
alertDialog.setPositiveButton("Close App", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
// Showing Alert Message
alertDialog.show();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
} so plz help me guys ........
解决方案
an easy way to send data to the server is by using the google volley library. http://developer.android.com/intl/zh-cn/training/volley/index.html
这篇关于如何发送位置服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文