使用GPS坐标的帮助,安卓系统

3
我正在使用以下代码获取我的位置,并将坐标打印在屏幕上。
package com.example.alpha;  

import android.app.Activity;  
import android.content.Context;  
import android.location.Location;  
import android.location.LocationListener; 
import android.location.LocationManager;  
import android.os.Bundle;  
import android.widget.Toast;  

public class alpha extends Activity   
{  
    private LocationManager lm;  
    private LocationListener locationListener;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 

        //---use the LocationManager class to obtain GPS locations---
        lm = (LocationManager) 
            getSystemService(Context.LOCATION_SERVICE);    

        locationListener = new MyLocationListener();

        lm.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            0, 
            0, 
            locationListener);   
    }

    public class MyLocationListener implements LocationListener 
    {
       public void onLocationChanged(Location loc) {


           double lat = loc.getLatitude();
           double lon = loc.getLongitude();
           Toast.makeText(getBaseContext(), "Location changed : alphaLat: " + lat + 
                   " alphaLng: " + lon, 
                   Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider, int status, 
            Bundle extras) {
            // TODO Auto-generated method stub
        }

    }        

}

问题在于我想使用纬度和经度的值,以便通过流发送它们。有什么建议可以在onLocationChanged方法之外获取坐标吗?

1个回答

2

不要将lat和lon声明为局部变量,而是将它们声明为类级别的变量。这样,您就可以在onLocationChanged方法之外访问这些值。

public class alpha extends Activity
{
         private LocationManager lm;
         private LocationListener locationListener;
         double lat;
         double lon;

  public class MyLocationListener implements LocationListener 
  {
   ...

   lat = loc.getLatitude();
   lon = loc.getLongitude();

   ........

他们是否仍然会在方法内部保留其值,并且该值不会传递到方法外部? - kotsosh
@kotsosh 没有理解你的问题。如果你想在类外访问变量,考虑使用 sharedpreferences 或单例对象。我使用单例对象在我的服务和活动之间传递值。 - GSree

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接