我当前的位置始终返回null。我怎样才能解决这个问题?

时间:2012-03-26 13:38:03

标签: android google-maps null location nullpointerexception

我正在尝试找到一个Android项目的当前位置。加载应用程序时,我的当前位置始终为null。我已经在清单等中设置了权限。当我找到当前位置时,我打算使用坐标来查找到地图上其他位置的距离。我的代码片段如下。为什么我总是得到一个空值?

locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);          
Criteria crit = new Criteria();     
towers = locMan.getBestProvider(crit, false);
location = locMan.getLastKnownLocation(towers);    

if (location != null) {                 
    System.out.println("Location is not null!");
    lat = (int) (location.getLatitude() *1E6);
    longi = (int) (location.getLongitude() * 1E6);
    GeoPoint ourLocation = new GeoPoint(lati, longi);
    OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String",
                                                            "2nd String");
    CustomPinpoint custom = new CustomPinpoint(d, MainMap.this);
    custom.insertPinpoint(overlayItem);
    overlayList.add(custom);
    overlayList.clear();
} else {
   System.out.println("Location is null! " + towers);
   Toast.makeText(MainMap.this, "Couldn't get provider",Toast.LENGTH_SHORT)
                                                                    .show();
}

7 个答案:

答案 0 :(得分:35)

getLastKnownLocation()使用之前由其他应用程序找到的位置。如果没有应用程序执行此操作,则getLastKnownLocation()将返回null。

您可以对代码执行一项操作,以便更有可能获得最后已知位置 - 迭代所有已启用的提供程序,而不仅仅是最佳提供程序。例如,

private Location getLastKnownLocation() {
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        ALog.d("last known location, provider: %s, location: %s", provider,
                l);

        if (l == null) {
            continue;
        }
        if (bestLocation == null
                || l.getAccuracy() < bestLocation.getAccuracy()) {
            ALog.d("found best last known location: %s", l);
            bestLocation = l;
        }
    }
    if (bestLocation == null) {
        return null;
    }
    return bestLocation;
}

如果您的应用无法在没有位置的情况下进行交易,并且如果没有最后的已知位置,则需要监听位置更新。你可以看看这个类的例子,

  

https://github.com/farble1670/autobright/blob/master/src/org/jtb/autobright/EventService.java

查看方法onStartCommand(),检查网络提供程序是否已启用。如果没有,它使用最后已知的位置。如果已启用,则会注册以接收位置更新。

答案 1 :(得分:8)

如果您在主类中使用以下方法找到设备的当前位置

public void find_Location(Context con) {
    Log.d("Find Location", "in find_location");
    this.con = con;
    String location_context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) con.getSystemService(location_context);
    List<String> providers = locationManager.getProviders(true);
    for (String provider : providers) {
        locationManager.requestLocationUpdates(provider, 1000, 0,
            new LocationListener() {

                public void onLocationChanged(Location location) {}

                public void onProviderDisabled(String provider) {}

                public void onProviderEnabled(String provider) {}

                public void onStatusChanged(String provider, int status,
                        Bundle extras) {}
            });
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            addr = ConvertPointToLocation(latitude, longitude);
            String temp_c = SendToUrl(addr);
        }
    }
}

并在清单文件中添加用户权限方法

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

答案 2 :(得分:0)

试试这个不会给你空当前位置

class GetLastLocation extends TimerTask {

    LocationManager mlocManager = (LocationManager) 
            getSystemService(Context.LOCATION_SERVICE);
    LocationListener mlocListenerTmp = new CustomLocationListener();
    private final Handler mLocHandler;

    public GetLastLocation(Handler mLocHandler) {
        this.mLocHandler = mLocHandler;
    }

    @Override
    public void run() {
        timer.cancel();
        mlocManager.removeUpdates(mlocListenerTmp);
        Location location = mlocManager
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        {
            if (mlocListenerTmp != null) {
                mlocManager.removeUpdates(mlocListenerTmp);
            }
            currentLocation = location;
        }
        if (location != null) {
            String message = String.format(
                "Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude());
            Log.d("loc", " :" + message);
            Bundle b = new Bundle();
            {
                b.putBoolean("locationRetrieved", true);
                {
                    Message msg = Message.obtain();
                    {
                        msg.setData(b);
                        mLocHandler.sendMessage(msg);
                    }
                }
            }
        } else {
            Log.d(
                "loc",
                ":No GPS or network signal please fill the location manually!");
            location = mlocManager
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                currentLocation = location;
                Bundle b = new Bundle();
                {
                    b.putBoolean("locationRetrieved", true);
                    {
                        Message msg = Message.obtain();
                        {
                            msg.setData(b);
                            mLocHandler.sendMessage(msg);
                        }
                    }
                }
            } else {
                Bundle b = new Bundle();
                {
                    b.putBoolean("locationRetrieved", false);
                    {
                        Message msg = Message.obtain();
                        {
                            msg.setData(b);
                            mLocHandler.sendMessage(msg);
                        }
                    }
                }
            }
        }
    }
}

像这样称呼它

timer.schedule(new GetLastLocation(mLocHandler), 3000);

和customLocationclass如下

public class CustomLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {
        loc.getLatitude();
        loc.getLongitude();
        currentLocation = loc;
        String Text = "My current location is: " + "Latitud = "
            + loc.getLatitude() + "Longitud = " + loc.getLongitude();
        Log.d("loc", "onLocationChanged" + Text);
    }

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

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

答案 3 :(得分:0)

如果您在marshmallow设备中试用它,请尝试手动为您的应用启用位置权限。

答案 4 :(得分:0)

使用以下方法打开您的GPS。它可以帮助您显示当前位置,而不会出现任何错误。在onCreate中调用它

public void displayLocationSettingsRequest(Context context, int requestCode) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API).build();
    googleApiClient.connect();

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(10000 / 2);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(result1 -> {
        final Status status = result1.getStatus();
        if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED)
            try {
                status.startResolutionForResult((Activity) context, requestCode);
            } catch (IntentSender.SendIntentException ignored) {
            }
    });

答案 5 :(得分:0)

如果您的提供商列表出现空错误,请更改...

List<String> providers = mLocationManager.getProviders(true);

到...

List<String> providers = locationManager.getAllProviders();

这对我有用,请确保您的AndroidManifest.xml文件中包含以下内容...

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

答案 6 :(得分:-1)

您是否尝试过反转代码?例如,if(location == null)然后打印该位置为null,否则打印位置不为null。我曾经遇到过这个问题,似乎已经解决了这个问题(我不知道为什么)。试试吧。

如果这不起作用,也许谷歌地图API返回空值,在这种情况下,它是GM-API或调用方法的问题。任何这些都可能是问题。

希望这有帮助,

-JXP