Android requestLocationUpdates with GPS null [英] Android requestLocationUpdates with GPS null

查看:62
本文介绍了Android requestLocationUpdates with GPS null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void getLocation(){
    locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getAllProviders();
    for (String provider : providers) {
        Log.e("GPS_provider: ", provider);
    }
    Criteria criteria = new Criteria();
    bestProvider = locationManager.getBestProvider(criteria, false);
    Log.e("Best_provider: ", bestProvider);
    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.
            Log.e("Loc_changed", ""+ location.getLatitude() + location.getLongitude());
            mLocation = location;
        }

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

        public void onProviderEnabled(String provider) {
            Log.e("Provider_enabled:", provider);
        }

        public void onProviderDisabled(String provider) {
            Log.e("Provider_disabled:", provider);

        }
    };
    // Register the listener with the Location Manager to receive location updates
    try {
        locationManager.requestLocationUpdates(bestProvider, 0, 0, locationListener);
        mLocation = locationManager.getLastKnownLocation(bestProvider);
        if (mLocation == null){
            mLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            Log.e("GPS network", "true");
        }
    } catch (SecurityException e){
        Log.e("GPS problem", "GPS problem "+e.getMessage());
    }
}

我正在尝试通过HTTP GET检索位置之前读取位置:

I'm trying to read position before doing an HTTP GET to retrieve my records:

private void loadBusinesses(){
    gpsMsg.setVisibility(View.INVISIBLE);
    getLocation();
    currentView = GEOVIEW;
    businessesList.nextUrl = "null";
    if (!businessesList.isEmpty()){
        Log.e("businessList ","not empty");
        businessesList.clear();
        notifyAdapter();
    }

    Double latitude;
    Double longitude;
    try{
        latitude = mLocation.getLatitude();
        longitude = mLocation.getLongitude();
    } catch (NullPointerException e){
        Log.e("GPS", "Location unavailable");
        gpsMsg.setVisibility(View.VISIBLE);
        swipeContainer.setRefreshing(false);
        return;
    }

}

即使我检查GPS是否已打开,当我尝试使用GPS位置时,我总是会得到null,然后它会从NETWORK获取位置. 由于这个原因,我试图将GPS设置设置为仅GPS",并且我得到NULL,所以没有位置. 我读了所有其他帖子,但我在GPS上一无所获.我正在使用USB调试在真实设备上进行仿真.

Even if i check if GPS is turned on, i always get null when i try to use GPS position, and then it takes position from NETWORK. For this reason i tried to setup GPS setting to "only GPS", and i get NULL, so no position. I read all other posts but i keep taking null on GPS. I'm emulating on a real device with USB Debug.

有什么主意吗?

推荐答案

我相信您对位置管理器的工作方式解释有误.

I believe you are interpreting wrong how the LocationManager works.

当您呼叫locationManager.requestLocationUpdates(bestProvider, 0, 0, locationListener)时,您只是在注册以接收位置更新,这通常需要一些时间(并且可能永远不会发生,正如CommonsWare指出的那样).此调用不会会立即为您提供更新的位置,因此,在下一行代码中,当您调用getLastKnownLocation()时,接收null是正常的行为.

When you call locationManager.requestLocationUpdates(bestProvider, 0, 0, locationListener) you are just registering to receive location updates, which normally takes some time to occur (and may never occur, as CommonsWare pointed out). This call does not gives you right away an updated location, so, in the next line of code, when you call getLastKnownLocation(), it's normal behavior to receive null.

也就是说,我认为处理您的情况的最佳方法是:

That said, I believe the best way to deal with your situation is this:

1-首先:检查getLastKnownLocation()是否返回null(如果所选的LocationProvider已经具有您应用程序或其他应用程序中的最新位置,它将在此处为您返回该位置.但是请注意:此位置可能是非常过时!).

1 - First: check whether getLastKnownLocation() returns null or not (if the chosen LocationProvider has already a recent location from your app or even from another app, it will return it for you here. But beware: this location could be very outdated!).

2-如果getLastKnownLocation()返回null,那么您将没有其他选择,只能请求一个全新的位置并等待其到达,这将在的方法onLocationChanged中发生LocationListener.因此,要执行此操作,您有两个选择:(a)调用requestSingleUpdate(),将一次为您返回更新的位置,或(b)调用requestLocationUpdates(),将注册locationManager接收定期的位置更新(并且会消耗更多电量).

2 - If getLastKnownLocation() returns null, then you will have no other option but to request a brand new location and wait for it to arrive, which will happen on the method onLocationChanged in the LocationListener. So, to do that you have two options: (a) call requestSingleUpdate(), which will return an updated location for you just one time, or (b) call requestLocationUpdates(), which will register the locationManager to receive periodical location updates (and will consume more battery).

3-在这两个选项中,当您收到位置更新时,将调用LocationListener中的方法onLocationChanged,然后您可以从该方法中调用loadBusinesses,并收到全新的位置.

3 - In both options, when you receive a location update, the method onLocationChanged in the LocationListener will be called and then you can call your loadBusinesses from this method, with the brand new location received.

希望这很清楚;)

-----编辑-----

----- EDIT -----

在调用requestSingleUpdaterequestLocationUpdates之前,还应该在运行时请求位置权限.为此,请使用以下代码段:

You should also request location permissions on runtime, before calling requestSingleUpdate or requestLocationUpdates. To do that, use this snippet:

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    // If permission is not granted, request it from user. When user responds, your activity will call method "onRequestPermissionResult", which you should override
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
} else {
    locationManager.requestSingleUpdate(bestProvider, locationListener, null)
}

如果之前未授予该权限,则系统将提示用户授予(或不授予)权限.因此,您还应该在活动中@Override方法onRequestPermissionResult,以检查用户是否授予了权限,然后正确响应.这是您应该重写的方法:

If the permission was not granted before, the user will be prompted to grant it (or not). So, you should also @Override the method onRequestPermissionResult in your activity, to check whether user granted the permission or not, and then respond properly. This is the method you should override:

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // PERMISSION WAS GRANTED
            } else {
                // USER DID NOT GRANT PERMISSION
            }
            break;
    }
}

这篇关于Android requestLocationUpdates with GPS null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆