簡體   English   中英

獲取經度和緯度值以發布到url-Android

[英]Get longitude and latitude values to post into url - Android

我正在創建一個提取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();
        }

    }

}

我以前從未使用過位置信息,所以我不確定我在這里做什么。 如果有人可以提出一些建議,我將不勝感激!

希望你不會忘記

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

在清單文件中。 本教程可以幫助您更好地理解。

編輯

Google已提供培訓以獲取當前位置。

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

您應該將位置變量的初始化移動到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 {
    ...
}

我在做同樣的事情,這對我有用! 但是,我請求的服務器是一個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! 我還沒有做完,所以看起來可能不多,但它確實有效,而且還使用geocoder從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) {

}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM