Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/225.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android中获取经纬度的正确方法_Android_Geolocation_Gps_Location - Fatal编程技术网

Android中获取经纬度的正确方法

Android中获取经纬度的正确方法,android,geolocation,gps,location,Android,Geolocation,Gps,Location,我需要在Android中以编程方式获取纬度和经度的正确方法。我浏览了不同的网站和论坛,但仍然找不到正确的。该程序应支持所有Android版本。我使用wifi将我的设备连接到网络。下面的实现创建了一个locationlistener,将更新的值记录为字符串,以方便提取。通过使用LocationManager,您可以抽象出用于检索位置的基本方法GPS/辅助GPS、wifi和手机发射塔 首先初始化: LocationManager lm = (LocationManager) getSystemSer

我需要在Android中以编程方式获取纬度和经度的正确方法。我浏览了不同的网站和论坛,但仍然找不到正确的。该程序应支持所有Android版本。我使用wifi将我的设备连接到网络。

下面的实现创建了一个locationlistener,将更新的值记录为字符串,以方便提取。通过使用LocationManager,您可以抽象出用于检索位置的基本方法GPS/辅助GPS、wifi和手机发射塔

首先初始化:

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
final myLocationListner ll = new myLocationListner();
位置侦听器:

public class myLocationListner implements LocationListener {

        public static String lattitude = "";
    public static String longitude = "";

    @Override
    public void onLocationChanged(Location loc) {
        String temp_lattitude = String.valueOf(loc.getLatitude());
        String temp_longitude = String.valueOf(loc.getLongitude());

        if(!("").equals(temp_lattitude))lattitude = temp_lattitude;
        if(!("").equals(temp_longitude))longitude = temp_longitude;
    }

    @Override
    public void onProviderDisabled(String arg0) {

    }

    @Override
    public void onProviderEnabled(String arg0) {

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {

    }

}

别担心,在我绞尽脑汁数天之后,我用了几行代码来获取经度和纬度值。。。我想这会让事情变得更好,谢谢你的建议

private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
List<String> providers = lm.getProviders(true);

/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;

for (int i=providers.length();i>=0;i--) {
    l = lm.getLastKnownLocation(providers.get(i));
    if (l != null) break;
}

double[] gps = new double[2];
if (l != null) {
    gps[0] = l.getLatitude();
    gps[1] = l.getLongitude();
}
return gps;}

不要忘记使用requestLocationUpdates注册该LocationListener,然后使用removeUpdates将其删除。这里是一个示例项目:谢谢你的建议Sameer。希望遵循它