Android 利用GPS获取经纬度

Android 利用GPS获取经纬度,android,Android,我正在尝试在移动设备上获取GPS纬度和经度。当选择设备的“使用无线网络”设置时,我下面的代码起作用——即,它以所需的方式提供所有信息——但当选择“使用GPS卫星”时,它就不起作用了,在这种情况下,我得不到任何信息 代码如下: void getLatitudeAndLongitude() { boolean gpsEnabled = false; LocationManager mLocMan = (LocationManager) getSystemService(Context

我正在尝试在移动设备上获取GPS纬度和经度。当选择设备的“使用无线网络”设置时,我下面的代码起作用——即,它以所需的方式提供所有信息——但当选择“使用GPS卫星”时,它就不起作用了,在这种情况下,我得不到任何信息

代码如下:

void getLatitudeAndLongitude() {
    boolean gpsEnabled = false;
    LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Log.e("mLocation#####", "" + mLocMan);

    try {
        gpsEnabled = mLocMan
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
    }
    boolean networkEnabled = false;
    try {
        networkEnabled = mLocMan
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }
    Location mCurrentLocation = null;

    // network*****************

    if (networkEnabled)
        mCurrentLocation = mLocMan
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    // gps********************
    if (gpsEnabled)
        mCurrentLocation = mLocMan
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);

    Log.d("current location", "" + mCurrentLocation);
    LocationProvider mGpsProv = null;

    if (mGpsProv == null && mLocMan != null) {
        mGpsProv = mLocMan.getProvider(LocationManager.GPS_PROVIDER);
    }

    if (mLocMan != null) {

        mylocationlistener mGpsLocListener = new mylocationlistener();
        mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                0 /* minTime ms */, 0 /* minDistance in meters */,
                mGpsLocListener);
        Log.d("Provoider1", "NETWORK_PROVIDER");
    }
    if (mLocMan != null && mGpsProv != null) {

        mylocationlistener mGpsLocListener = new mylocationlistener();
        mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                0 /* minTime ms /, 0 / minDistance in meters */, 0,
                mGpsLocListener);
        Log.d("Provoider2", "GPS_PROVIDER");
    }

}

class mylocationlistener implements LocationListener {

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {

            latitude = String.valueOf(location.getLatitude());
            longitude = String.valueOf(location.getLongitude());

            Log.e("location==", "" + location);
            Log.e("getLatitude", location.getLatitude() + "");
            Log.e("getLongitude", location.getLongitude() + "");

            if (GlobalConfig.DEBUG)
                Log.d("setUpIndividualWork", "location==" + location);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                }
            }, 1000);

            onGPSUpdate(location);

            Geocoder gcd = new Geocoder(setUpIndividualWorkOut.this,
                    Locale.getDefault());
            List<Address> addresses = null;
            try {
                addresses = gcd.getFromLocation(location.getLatitude(),
                        location.getLongitude(), 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (addresses != null && addresses.size() > 0) {
                userCurrentLocation = addresses.get(0).getLocality();
                Log.e("current location by GPS ", ""
                        + addresses.get(0).getLocality());
            }
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}
void GetLatitudeAndLongLitence(){
布尔gpsEnabled=false;
LocationManager mLocMan=(LocationManager)getSystemService(Context.LOCATION\u服务);
Log.e(“位置”、“+mLocMan”);
试一试{
gpsEnabled=mLocMan
.isprovidenabled(LocationManager.GPS\U提供商);
}捕获(例外情况除外){
}
布尔值networkEnabled=false;
试一试{
networkEnabled=mLocMan
.isProviderEnabled(LocationManager.NETWORK_提供商);
}捕获(例外情况除外){
}
位置mCurrentLocation=null;
//网络*****************
if(可联网)
mCurrentLocation=mLocMan
.getLastKnownLocation(LocationManager.网络提供商);
//全球定位系统********************
如果(gpsEnabled)
mCurrentLocation=mLocMan
.getLastKnownLocation(LocationManager.GPS\U提供商);
Log.d(“当前位置”,“mCurrentLocation”);
LocationProvider mGpsProv=null;
如果(mGpsProv==null&&mLocMan!=null){
mGpsProv=mLocMan.getProvider(LocationManager.GPS\u PROVIDER);
}
if(mLocMan!=null){
mylocationlistener mGpsLocListener=新建mylocationlistener();
mLocMan.RequestLocationUpdate(LocationManager.NETWORK\u提供程序,
0/*分钟毫秒*/,0/*分钟距离,以米为单位*/,
mGpsLocListener);
Log.d(“Provoider1”、“网络提供商”);
}
if(mLocMan!=null&&mGpsProv!=null){
mylocationlistener mGpsLocListener=新建mylocationlistener();
mLocMan.RequestLocationUpdate(LocationManager.GPS\U提供程序,
0/*minTime ms/,0/米距离*/,0,
mGpsLocListener);
Log.d(“Provoider2”、“GPS_提供商”);
}
}
类mylocationlistener实现LocationListener{
@凌驾
已更改位置上的公共无效(位置){
如果(位置!=null){
latitude=String.valueOf(location.getLatitude());
经度=String.valueOf(location.getLongitude());
Log.e(“位置==”,“”+位置);
Log.e(“getLatitude”,location.getLatitude()+”);
Log.e(“getLongitude”,location.getLongitude()+”);
if(GlobalConfig.DEBUG)
Log.d(“setUpIndividualWork”,“location==”+location);
new Handler().postDelayed(new Runnable()){
@凌驾
公开募捐{
}
}, 1000);
ONGPUPDATE(位置);
地理编码器gcd=新地理编码器(setUpIndividualWorkOut.this,
Locale.getDefault());
列表地址=空;
试一试{
addresses=gcd.getFromLocation(location.getLatitude(),
location.getLongitude(),1);
}捕获(IOE异常){
e、 printStackTrace();
}
if(addresses!=null&&addresses.size()>0){
userCurrentLocation=addresses.get(0.GetLocation();
Log.e(“GPS当前位置”
+addresses.get(0.getLocation());
}
}
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra){
}
}
我将非常感谢您的回复。

我这样使用它: 类LocationHelper:

public class LocationManagerHelper {
private static final String TAG = LocationManagerHelper.class.getSimpleName();
private Context mContext;

private LocationManager mLocationManager;
private GeoUpdateHandler mLocationListener = new GeoUpdateHandler();

public LocationManagerHelper(Context context) {
    this.mContext = context;
}


public GeoUpdateHandler GetLocationListener() {
    return mLocationListener;
}

public void SetLocationManager(LocationManager locationManager) {
    mLocationManager = locationManager;
}

public LocationManager GetLocationManager() {
    return mLocationManager;
}


public void Stop() {
    if (mLocationManager != null) {
        mLocationManager.removeUpdates(mLocationListener);
    }
}

private class GeoUpdateHandler implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {
        String longitude = "Longitude: " + loc.getLongitude();
        Log.v(TAG, longitude);
        String latitude = "Latitude: " + loc.getLatitude();
        Log.v(TAG, latitude);
    }

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

    }

    @Override
    public void onProviderEnabled(String s) {
    }

    @Override
    public void onProviderDisabled(String s) {
    }
}
}

试试这个

@Override

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);



LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListener lmh = new MyLocationListener();

String mlocProvider;
Criteria hdCrit = new Criteria();

hdCrit.setAccuracy(Criteria.ACCURACY_COARSE);

mlocProvider = locationManager.getBestProvider(hdCrit, true);

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1000, lmh);
Location currentLocation = locationManager.getLastKnownLocation(mlocProvider);

double currentLatitude = currentLocation.getLatitude();
double currentLongitude = currentLocation.getLongitude();
Log.e("lat",""+currentLatitude);
Log.e("lng",""+currentLongitude);
}

public class MyLocationListener implements LocationListener

{

public void onLocationChanged(Location loc)

{

loc.getLatitude();

loc.getLongitude();

String Text = "My current location is:" +

"Latitud = "+ loc.getLatitude() +

"Longitud = " + loc.getLongitude();

Toast.makeText( getApplicationContext(),

Text,

Toast.LENGTH_SHORT).show();

}



public void onProviderDisabled(String provider)

{

Toast.makeText( getApplicationContext(),

"Gps Disabled",

Toast.LENGTH_SHORT ).show();

}


public void onProviderEnabled(String provider)

{

Toast.makeText( getApplicationContext(),

"Gps Enabled",

Toast.LENGTH_SHORT).show();

}



public void onStatusChanged(String provider, int status, Bundle extras)

{

}

}/* End of Class MyLocati
试试这个:

package loca.loca;

import java.util.Timer;
import java.util.TimerTask;
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 LocationActivity extends Activity {

    double x,y;

    Timer timer;
    LocationManager lm;
    boolean gps_enabled = false;
    boolean network_enabled = false;

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


            lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);



            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
            network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);



        if (!gps_enabled && !network_enabled) {  Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, "nothing is enabled", duration);
            toast.show();

        }




        if (gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                    locationListenerGps);
        if (network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                    locationListenerNetwork);
         timer=new Timer();
         timer.schedule(new GetLastLocation(), 20000);

    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer.cancel();
            x =location.getLatitude();
            y = location.getLongitude();
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);

            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, "gps enabled "+x + "\n" + y, duration);
            toast.show();
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer.cancel();
            x = location.getLatitude();
            y = location.getLongitude();
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);

            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, "network enabled"+x + "\n" + y, duration);
            toast.show();
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                {x = gps_loc.getLatitude();
                y = gps_loc.getLongitude();
                  Context context = getApplicationContext();
                    int duration = Toast.LENGTH_SHORT;
                    Toast toast = Toast.makeText(context, "gps lastknown "+x + "\n" + y, duration);
                    toast.show();
                }
                 else
                {x = net_loc.getLatitude();
                y = net_loc.getLongitude();
                Context context = getApplicationContext();
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(context, "network lastknown "+x + "\n" + y, duration);
                toast.show();

                }

             }

             if(gps_loc!=null){
                  {x = gps_loc.getLatitude();
                y = gps_loc.getLongitude();
                  Context context = getApplicationContext();
                    int duration = Toast.LENGTH_SHORT;
                    Toast toast = Toast.makeText(context, "gps lastknown "+x + "\n" + y, duration);
                    toast.show();
                  }

             }
             if(net_loc!=null){
                {x = net_loc.getLatitude();
                y = net_loc.getLongitude();
              Context context = getApplicationContext();
              int duration = Toast.LENGTH_SHORT;
              Toast toast = Toast.makeText(context, "network lastknown "+x + "\n" + y, duration);
                toast.show();

                }
             }
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, "no last know avilable", duration);
            toast.show();

}
}}

当你试着这样做的时候,你能清楚地看到天空吗?GPS通常在某些
s的行内不起作用:如果“networkEnabled”和“gpsEnabled”都是“true”,那么您将两次获得最后一个已知位置。另外,如果mLocMan和mGpsProv都为null,则您将请求这些更新两次。
package loca.loca;

import java.util.Timer;
import java.util.TimerTask;
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 LocationActivity extends Activity {

    double x,y;

    Timer timer;
    LocationManager lm;
    boolean gps_enabled = false;
    boolean network_enabled = false;

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


            lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);



            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
            network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);



        if (!gps_enabled && !network_enabled) {  Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, "nothing is enabled", duration);
            toast.show();

        }




        if (gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                    locationListenerGps);
        if (network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                    locationListenerNetwork);
         timer=new Timer();
         timer.schedule(new GetLastLocation(), 20000);

    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer.cancel();
            x =location.getLatitude();
            y = location.getLongitude();
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);

            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, "gps enabled "+x + "\n" + y, duration);
            toast.show();
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer.cancel();
            x = location.getLatitude();
            y = location.getLongitude();
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);

            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, "network enabled"+x + "\n" + y, duration);
            toast.show();
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                {x = gps_loc.getLatitude();
                y = gps_loc.getLongitude();
                  Context context = getApplicationContext();
                    int duration = Toast.LENGTH_SHORT;
                    Toast toast = Toast.makeText(context, "gps lastknown "+x + "\n" + y, duration);
                    toast.show();
                }
                 else
                {x = net_loc.getLatitude();
                y = net_loc.getLongitude();
                Context context = getApplicationContext();
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(context, "network lastknown "+x + "\n" + y, duration);
                toast.show();

                }

             }

             if(gps_loc!=null){
                  {x = gps_loc.getLatitude();
                y = gps_loc.getLongitude();
                  Context context = getApplicationContext();
                    int duration = Toast.LENGTH_SHORT;
                    Toast toast = Toast.makeText(context, "gps lastknown "+x + "\n" + y, duration);
                    toast.show();
                  }

             }
             if(net_loc!=null){
                {x = net_loc.getLatitude();
                y = net_loc.getLongitude();
              Context context = getApplicationContext();
              int duration = Toast.LENGTH_SHORT;
              Toast toast = Toast.makeText(context, "network lastknown "+x + "\n" + y, duration);
                toast.show();

                }
             }
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, "no last know avilable", duration);
            toast.show();

}
}}