LocationManager,GPS和网络提供商......都被触发了吗?

时间:2013-09-24 10:31:42

标签: android network-programming gps android-location

此代码:

ServiceListener mlistener = new SosServiceListener(getApplicationContext());

manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

manager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mlistener, null);
manager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, mlistener, null);

将侦听器附加到两个事件。事实是:如果两个事件都被触发,那么监听器被调用两次?如果是的话,你会如何防止它?

谢谢!

2 个答案:

答案 0 :(得分:2)

这是我用于其中一个项目并且完美运行的内容:

public Location getLocation() {
        try {
            mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);

            // getting GPS status
            boolean isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            boolean isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,  MIN_TIME_BW_UPDATES,  MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (mLocationManager != null) {
                        location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            lat = location.getLatitude();
                            lng = location.getLongitude();
                        }
                    }
                }
                //get the location by gps
                if (isGPSEnabled) {
                    if (location == null) {
                        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (mLocationManager != null) {location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                lat = location.getLatitude();
                                lng = location.getLongitude();
                            }
                        }
                    }
                }
            }

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

        return location;
    }

答案 1 :(得分:0)

如果您认为设备将在安装了Google Play的设备上运行,那么更好的方法是使用此服务:https://developer.android.com/training/location/retrieve-current.html