Android 获取位置(GPS和网络)时出错

Android 获取位置(GPS和网络)时出错,android,geolocation,gps,Android,Geolocation,Gps,我想使用以下代码获取我的应用程序中的位置: public Location getLocation() { boolean isGPSEnabled = false; boolean isNetworkEnabled = false; try { // Getting GPS and Network status isGPSEnabled = locationManager.isProviderEnab

我想使用以下代码获取我的应用程序中的位置:

public Location getLocation() {     

    boolean isGPSEnabled     = false;
    boolean isNetworkEnabled = false;

    try {   

        // Getting GPS and Network status
        isGPSEnabled     = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) return null;

        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        location                = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if ((location != null && (location.getTime() + 60000 < System.currentTimeMillis())) || 
                location == null){
            location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }                           

    } catch (Exception e) {
        e.printStackTrace(); 
        return null;
    }

    return location;
}

我想你必须通过调用一个请求来触发它。。。函数。

如果设备尚未找到位置,它将返回null

我打赌,如果你打开谷歌地图,让它在打开你的应用程序之前找到你,它会像预期的那样工作

看看我对你的回答。 这是一个关于如何实现回调的示例,以便在位置可用时立即通知您

public void startLocation() {

    try {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);    

    } catch (Exception e) {
        e.printStackTrace(); 
    }
}