Java 获取要发布到url中的经度和纬度值-Android

Java 获取要发布到url中的经度和纬度值-Android,java,android,xml,eclipse,gps,Java,Android,Xml,Eclipse,Gps,我正在创建一个能提取XML数据的Android应用程序。我希望能够使用经度和纬度值发布到web链接中,以获取用户当前位置的特定XML数据 以下是迄今为止我的代码,它不起作用: public class GeoSplashActivity extends Activity { LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location location = lm

我正在创建一个能提取
XML
数据的
Android
应用程序。我希望能够使用经度和纬度值发布到web链接中,以获取用户当前位置的特定
XML
数据

以下是迄今为止我的代码,它不起作用:

public class GeoSplashActivity extends Activity {
    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    double longitude = location.getLongitude();
    double latitude = location.getLatitude();
    private String GEORSSFEEDURL = "http://www.socialalertme.com/mobilealerts.xml?lat="+latitude+"lng="+longitude+"&distance=20";
    GeoRSSFeed feed3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash2);
        ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conMgr.getActiveNetworkInfo() == null
                && !conMgr.getActiveNetworkInfo().isConnected()
                && !conMgr.getActiveNetworkInfo().isAvailable()) {
            // No connectivity - Show alert
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(
                    "Unable to reach server, \nPlease check your connectivity.")
                    .setTitle("TD RSS Reader")
                    .setCancelable(false)
                    .setPositiveButton("Exit",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int id) {
                                    finish();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            // Connected - Start parsing
            new AsyncLoadXMLFeed().execute();
        }
    }

    private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            // Obtain feed
            GeoDOMParser myParser = new GeoDOMParser();
            feed3 = myParser.parseXml(GEORSSFEEDURL);
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            Bundle bundle = new Bundle();
            bundle.putSerializable("feed", feed3);

            // launch List activity
            Intent intent = new Intent(GeoSplashActivity.this, GeoListActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);

            // kill this activity
            finish();
        }

    }

}
公共类GeoPlashactivity扩展活动{
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION\u服务);
Location Location=lm.getLastKnownLocation(LocationManager.GPS\U提供程序);
double longitude=location.getLongitude();
双纬度=location.getLatitude();
专用字符串GEORSSFEEDURL=”http://www.socialalertme.com/mobilealerts.xml?lat=“+纬度+”lng=“+经度+”&距离=20”;
GeoRSSFeed-feed3;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.splash2);
ConnectivityManager conMgr=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_服务);
如果(conMgr.getActiveNetworkInfo()==null
&&!conMgr.getActiveNetworkInfo().isConnected()
&&!conMgr.getActiveNetworkInfo().isAvailable()){
//无连接-显示警报
AlertDialog.Builder=新建AlertDialog.Builder(此);
builder.setMessage(
“无法访问服务器,\n请检查您的连接。”)
.setTitle(“TD RSS阅读器”)
.setCancelable(错误)
.setPositiveButton(“退出”,
新建DialogInterface.OnClickListener(){
@凌驾
公共void onClick(对话框接口对话框,
int id){
完成();
}
});
AlertDialog alert=builder.create();
alert.show();
}否则{
//连接启动解析
新建AsyncLoadXMLFeed().execute();
}
}
私有类AsyncLoadXMLFeed扩展了AsyncTask{
@凌驾
受保护的Void doInBackground(Void…参数){
//获取饲料
GeoDOMParser myParser=新的GeoDOMParser();
feed3=myParser.parseXml(GEORSSFEEDURL);
返回null;
}
@凌驾
受保护的void onPostExecute(void结果){
super.onPostExecute(结果);
Bundle=新Bundle();
bundle.putSerializable(“feed”,feed3);
//启动列表活动
意向意向=新意向(GeoPlashactivity.this、GeoListActivity.class);
意向。额外支出(捆绑);
星触觉(意向);
//终止此活动
完成();
}
}
}

我以前从未使用过位置信息,所以我不完全确定我在这里做什么。如果有人能给我一些建议,我会非常感激

希望你没有忘记

<uses-permission android:name=“android.permission.ACCESS_FINE_LOCATION”></uses-permission>

在您的清单文件中。可以帮助你更好地理解

编辑


Google已经提供了获取当前位置的方法。

您应该将位置变量的初始化移动到
onCreate
方法。您还应该检查
位置!=空

//Get coordinates if available:
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location loc;
double latitude=0,longitude=0;
if (  ( loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) )!=null  ){
        latitude = loc.getLatitude();
    longitude = loc.getLongitude();
}else if( ( loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) )!=null  ){
    latitude = loc.getLatitude();
    longitude = loc.getLongitude();
}
//If any coordinate value is recieved, use it.
if(latitude!=0 || longitude!=0){
    String latitude = String.valueOf(latitude);
        String longitude = String.valueOf(longitude);
        //TODO post into url 
}       
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
    longitude = location.getLongitude();
    latitude = location.getLatitude();
    GEORSSFEEDURL = "http://www.socialalertme.com/mobilealerts.xml?lat="+latitude+"lng="+longitude+"&distance=20";
} else {
    ...
}

我也在做同样的事情,这对我很有用! 但是,我请求的服务器是node.js服务器,数据是JSON格式的

public class GetWeatherDataRest extends AsyncTask<Void, Void, String> {
private static final String TAG = "GetWeatherDataRest";

// get lat and long from main activity
double lat = MyActivity.lat;
double lng = MyActivity.lng;

// the url
String url = "http://ThisIsTheAddress/weather/5days?lat="+lat+"&lng="+lng;
public MyActivity context;
private List<Weather> posts;

public GetWeatherDataRest(MyActivity activity){
    this.context = activity;
}

@Override
protected String doInBackground(Void... params) {

    try {
        //Create an HTTP client
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);

        //Perform the request and check the status code
        HttpResponse response = client.execute(get);
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();

            try {
                //Read the server response and attempt to parse it as JSON
                Reader reader = new InputStreamReader(content);
                GsonBuilder gsonBuilder = new GsonBuilder();
                gsonBuilder.setDateFormat("M/d/yy hh:mm a");
                Gson gson = gsonBuilder.create();
                posts = new ArrayList<Weather>();
                posts = Arrays.asList(gson.fromJson(reader, Weather[].class));
                content.close();
            } catch (Exception ex) {
                Log.e(TAG, "Failed to parse JSON due to: " + ex);
            }
        } else {
            Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
        }
    } catch(Exception ex) {
        Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
    }
    return null;
}

@Override
protected void onPostExecute(String result) {

    context.updateFields(posts);

}
公共类GetWeatherDataRest扩展异步任务{
私有静态最终字符串标记=“GetWeatherDataRest”;
//从主要活动中获取lat和long
双lat=MyActivity.lat;
双液化天然气=MyActivity.lng;
//网址
字符串url=”http://ThisIsTheAddress/weather/5days?lat=“+lat+”&lng=“+lng;
公共活动背景;
私人名单员额;
公共GetWeatherDataRest(MyActivity活动){
这个上下文=活动;
}
@凌驾
受保护字符串doInBackground(无效…参数){
试一试{
//创建一个HTTP客户端
HttpClient=new DefaultHttpClient();
HttpGet=新的HttpGet(url);
//执行请求并检查状态代码
HttpResponse response=client.execute(get);
StatusLine StatusLine=response.getStatusLine();
if(statusLine.getStatusCode()==200){
HttpEntity=response.getEntity();
InputStream内容=entity.getContent();
试一试{
//读取服务器响应并尝试将其解析为JSON
Reader Reader=新的InputStreamReader(内容);
GsonBuilder GsonBuilder=新的GsonBuilder();
gsonBuilder.setDateFormat(“M/d/yy hh:mm a”);
Gson-Gson=gsonBuilder.create();
posts=newarraylist();
posts=Arrays.asList(gson.fromJson(reader,Weather[].class));
content.close();
}捕获(例外情况除外){
Log.e(标记“由于“+ex”,无法解析JSON);
}
}否则{
Log.e(标记“服务器响应状态代码:”+statusLine.getStatusCode());
}
}捕获(例外情况除外){
Log.e(标记“由于“+ex”,无法发送HTTP POST请求);
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
上下文。更新字段(帖子);
}
}

好的!这是我的GpsFragment,在这里我可以得到lng和lat! 我还没有完成这项工作,所以它看起来可能不太像,但它是有效的,它还提供了一个来自lng&lat使用地理编码器的地址

您应该实现LocationListener

public class GpsFragment extends Fragment implements LocationListener{

public Location location;
LocationManager locationManager;
String provider;

List<Address> mAddresses;

TextView mAddress1;
TextView mAddress2;

public static double lat;
public static double lng;

private static final String TAG = "MyGps";


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View myInflatedView = inflater.inflate(R.layout.gps_fragment, container,false);

    mAddress1 = (TextView) myInflatedView.findViewById(R.id.address_text);
    mAddress2 = (TextView) myInflatedView.findViewById(R.id.address_text2);

    locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    locationManager.requestLocationUpdates(provider, 100, 1, this);

    if(location != null){
        onLocationChanged(location);
        Log.v(TAG, "Location available!");
    }
    else{
        mAddress1.setText("No location");
        Log.e(TAG, "Location not available!");
    }

    return myInflatedView;

}

// So i think this is what you need! the 'onLocationChanged' 
@Override
public void onLocationChanged(Location location) {
    this.location = location;
    lat = location.getLatitude();
    lng = location.getLongitude();

    Geocoder mLocation = new Geocoder(getActivity().getApplicationContext(), Locale.getDefault());
    try {
        mAddresses = mLocation.getFromLocation(lat, lng, 1);

        if(mAddresses != null) {
            Address returnedAddress = mAddresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
            for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
            }
            // mAddress.setText(strReturnedAddress.toString());

            //mAddress1.setText("lat"+lat);
            //mAddress2.setText("lng"+lng);

             mAddress1.setText("Address: "+returnedAddress.getAddressLine(0).toString());
             mAddress2.setText("City: "+returnedAddress.getAddressLine(1).toString());
        }
        else{
            // mAddress.setText("No Address returned!");
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        //mAddress.setText("Cannot get Address!");
    }

    ((MyActivity)getActivity()).fetchData();
}


@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}
公共类GpsFragment扩展片段实现LocationListener{
公共场所;
地点经理地点经理;
字符串提供者;
列出疯子;
文本视图1;
文本视图2;
平民的