获取经度和纬度值以发布到网址 - Android

时间:2014-04-04 10:48:43

标签: java android xml eclipse gps

我正在创建一个提取Android数据的XML应用。我希望能够使用经度和纬度值发布到网络链接中,以获取用户当前位置的特定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();
        }

    }

}

我之前从未使用过这些位置,所以我不完全确定我在这里做什么。如果有人能给出一些指示,我真的很感激!

4 个答案:

答案 0 :(得分:0)

希望你不要忘记

<uses-permission android:name=“android.permission.ACCESS_FINE_LOCATION”></uses-permission>
清单文件中的

This tutorial可以帮助您更好地理解。

修改

Google已提供Training来获取当前位置。

答案 1 :(得分:0)

//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 
}       

答案 2 :(得分:0)

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

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 {
    ...
}

答案 3 :(得分:0)

我正在做同样的事情,这对我有用! 但是,我要求的服务器是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);

}

}

奥基!这是我的GpsFragment,我得到了lng和lat! 我还没有完成这个,所以它看起来可能不是很多,但是它有效,它也提供了一个来自lng&amp; 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) {

}

}