How to get location when it changes

前端 未结 4 1382
温柔的废话
温柔的废话 2021-01-25 02:03

I would like to know there is a way to get location if only it changes? I know android provides this http://developer.android.com/training/location/receive-location-updates.html

4条回答
  •  时光取名叫无心
    2021-01-25 02:28

    I've searched for this article so many times! and I've found something like this but it's not pretty accurate although maybe this strategy help you, but I didn't found anything useful unless the other answers that friends gave you, so here's how I use it, It called PhoneStateListener :

    first you need to add the permissions:

    
    
    public class LocationService extends PhoneStateListener {
        private TelephonyManager telephonyManager;
        private boolean isLocationChanged;
    
        public LocationService(Context context) {
            telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    
            if (telephonyManager != null){
                isLocationChanged= telephonyManager.isNetworkRoaming();
                telephonyManager.listen(this,PhoneStateListener.LISTEN_CELL_LOCATION);
            }
        }
    
        public boolean locationChanged(){
            return isLocationChanged;
        }
    
        void unregisterListener(){
            telephonyManager.listen(this,PhoneStateListener.LISTEN_NONE);
        }
    
        @Override
        public void onCellLocationChanged(CellLocation location) {
            if (location != null){
                isLocationChanged = true;
            }
        }
    }
    

    according to the documentations:

    A listener class for monitoring changes in specific telephony states on the device, including service state, signal strength, message waiting indicator (voicemail), and others.

    Override the methods for the state that you wish to receive updates for, and pass your PhoneStateListener object, along with bitwise-or of the LISTEN_ flags to TelephonyManager#listen. Methods are called when the state changes, as well as once on initial registration.

    I'm not pretty sure of it's work yet, so please let me know if it works fine for you! :)

    here is another example : Add PhoneStateListener

提交回复
热议问题