【问题标题】:Toggle between network and GPS provider on service not on activity在网络和 GPS 提供商之间切换服务而不是活动
【发布时间】:2013-08-23 08:08:17
【问题描述】:

我想在 android 中作为后台服务持续跟踪用户位置,我可以使用后台服务和广播接收器来实现它,但无法弄清楚如何根据可用性在网络和 gps 提供商之间切换。

backgroundService.java

 @Override

        public int onStartCommand(Intent intent, int flags, int startId) {
        mylistner = new NewLocationListener(getBaseContext());

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        criteria.setCostAllowed(true);
        LocationManager locManager = (LocationManager) getBaseContext()
        .getSystemService(Context.LOCATION_SERVICE);
        String bestProvider = locManager.getBestProvider(criteria, false);
            Toast.makeText(getBaseContext(), "Best Provider "+bestProvider, Toast.LENGTH_SHORT).show();
        locManager.requestLocationUpdates(bestProvider, 1000, 5, mylistner);
        Toast.makeText(getBaseContext(), "Successfully Called", Toast.LENGTH_SHORT).show();
        return START_STICKY;
    }

最初 bestProvider 将有 gps 或网络,但如果它最初是 gps,然后如果用户关闭 gps,它应该使用网络给我协调。同样,如果用户打开 gps,则位置提供者应该来自 gps。

在服务上有 onProviderEnabled 和 onProviderDisabled 方法如何使用它们来达到目的

作为堆栈溢出中许多类似问题的解决方案,我不想从一开始就同时发送网络和 gps 提供商,我想根据可用性进行切换。 在服务中是否可以实现。 提前致谢

【问题讨论】:

    标签: android service gps locationlistener


    【解决方案1】:

    这可以帮助你重新思考问题:

    public class GPSTracker extends Service implements android.location.LocationListener {
        /**
         * ¨PRIVATE ATTRIBUTES
         */
        // log
        private static final String TAG                             = GPSTracker.class.getSimpleName();
        //
        private Context             _context;
        private static GPSTracker   _instance;
        // The minimum distance to change Updates in meters
        private static final long   MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;                                // meters
        // The minimum time between updates in milliseconds
        private static final long   MIN_TIME_BW_UPDATES             = 1000 * 30 * 1;                    // minute
        // Declaring a Location Manager
        protected LocationManager   _locationManager;
        /**
         * PUBLIC ATTRIBUTES
         */
        boolean                     _isGPSEnabled                   = false;
        boolean                     _isNetworkEnabled               = false;
        boolean                     _canGetLocation                 = false;
        public Location             _location;
        double                      _latitude;
        double                      _longitude;
    
        public GPSTracker() {
    
            _context = null;
        }
    
        public static GPSTracker getInstance() {
    
            if (_instance == null) {
                _instance = new GPSTracker();
            }
            return _instance;
        }
    
        public void set_context(Context context) {
    
            this._context = context;
        }
    
        public Location getLocation(Context context) {
    
            _context = context;
            try {
                _locationManager = (LocationManager) _context.getSystemService(LOCATION_SERVICE);
                _isGPSEnabled = _locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                _isNetworkEnabled = _locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                if (!_isGPSEnabled && !_isNetworkEnabled) {
                    // no network provider is enabled
                }
                else {
                    this._canGetLocation = true;
                    if (_isNetworkEnabled) {
                        _locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("Network", "Network");
                        if (_locationManager != null) {
                            _location = _locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (_location != null) {
                                _latitude = _location.getLatitude();
                                _longitude = _location.getLongitude();
                            }
                        }
                    }
                    // if GPS Enabled get lat/long using GPS Services
                    if (_isGPSEnabled) {
                        if (_location == null) {
                            _locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS Enabled");
                            if (_locationManager != null) {
                                _location = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (_location != null) {
                                    _latitude = _location.getLatitude();
                                    _longitude = _location.getLongitude();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e) {
                // TODO: ERROR getLocation
            }
            return _location;
        }
    
        public void stopUsingGPS() {
    
            if (_locationManager != null) {
                _locationManager.removeUpdates(GPSTracker.this);
            }
        }
    
        public double getLatitude() {
    
            if (_location != null) {
                _latitude = _location.getLatitude();
            }
            return _latitude;
        }
    
        public double getLongitude() {
    
            if (_location != null) {
                _longitude = _location.getLongitude();
            }
            return _longitude;
        }
    
        /**
         * Function to check GPS/wifi enabled
         * 
         * @return boolean
         */
        public boolean canGetLocation() {
    
            return this._canGetLocation;
        }
    
        /**
         * Function to show settings alert dialog On pressing Settings button will lauch Settings Options
         */
        public void showSettingsAlert(String title, String msg) {
    
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(_context);
            alertDialog.setTitle(title);
            alertDialog.setMessage(msg);
            // Settings button
            alertDialog.setPositiveButton("Paramètres", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
    
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    _context.startActivity(intent);
                }
            });
            // cancel button
            alertDialog.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
    
                    dialog.cancel();
                }
            });
            // show
            alertDialog.show();
        }
    
        @Override
        public void onLocationChanged(Location location) {
    
            Log.i(TAG, "onLocationChanged--TRACKER--" + location.getLatitude() + " / " + location.getLongitude());
        }
    
        @Override
        public void onProviderDisabled(String provider) {
    
        }
    
        @Override
        public void onProviderEnabled(String provider) {
    
        }
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
    
        }
    
        @Override
        public IBinder onBind(Intent arg0) {
    
            return null;
        }
    }
    

    【讨论】:

    • 感谢您的宝贵时间,但也想在这里知道您正在使用网络和 GPS 提供的同时不能一次完成一个。
    • 当我调用 gtLocation() 时,无论网络是否可用,我都会使用它,否则我使用 3G/... 您可以在调用函数(布尔值 useNetwork)时使用参数更改它,例如那么就做一个 if(useNetwork)/else ?
    猜你喜欢
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    相关资源
    最近更新 更多