How to get location when it changes

别说谁变了你拦得住时间么 提交于 2019-12-02 07:03:26
 protected void updateNotification() {
         LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
         LocationListener locationListener = new MyLocationlistener();

         lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, normallocationwait, 0.250f, locationListener);
         location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
   }

   private class MyLocationlistener implements LocationListener {

     public void onLocationChanged(Location location){
         if(location!=null){
             if(location.hasAccuracy()){
                   dumpLocation(location);
             }else{
                   dumpLocation(location);
            }
         } 
     }

     public void onProviderDisabled(String provider){
         Log.v("Loc Update","\nProvider disabled: " + provider);
     }

     public void onProviderEnabled(String provider){
         Log.v("Loc Update","\nProvider enabled: " + provider);
     }

     public void onStatusChanged(String provider, int status, Bundle extras){
         Log.v("Loc Update","\nProvider status changed: " + provider + ", status="
                    + status + ", extras=" + extras);
     }
// try this way
// declaration
public static LocationManager mlocManager;
public static LocationListner mListner;
private static String latitude;
public static String longitude;

//initialization
try {
    if (mlocManager == null)
            mlocManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
    if (mListner == null)
            mListner = new LocationListner();
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    try {
                        try {
                            mlocManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, mListner);
                        } catch (Throwable e) {
                            e.printStackTrace();
                        }

                        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mListner);
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    try {
                        mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mListner);
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }

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

//listener
class LocationListner implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            setLatitude("" + location.getLatitude());
            setLongitude("" + location.getLongitude());
            setCurrentLocation(location);
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

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

}
// Setter
public void setLatitude(String latitide) {
    this.latitude = latitide;
}
// Getter
public String getLatitude() {

    try {
        if (latitude != null) {
            return latitude;
        }
        if(mlocManager==null)
        {
            mlocManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
        }
        Location loc = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (loc == null) {
            loc = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (loc == null) {
                loc = mlocManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
            }
            if (loc != null) {
                    return "" + loc.getLatitude();
            }
            } else {
                    return "" + loc.getLatitude();
            }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "0";
}
  // Setter
public void setLongitude(String longitude) {
    this.longitude = longitude;
}
// Getter
public String getLongitude() {
    try {
        if (longitude != null) {
            return longitude;
        }
        if(mlocManager==null)
        {
            mlocManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
        }
        Location loc = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (loc == null) {
            loc = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (loc == null) {
                loc = mlocManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
            }
            if (loc != null) {
                return "" + loc.getLongitude();
            }
            } else {
                return "" + loc.getLongitude();
            }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "0";
}

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:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
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

This method requires GooglePlayService, and it doesn't need much power, maybe you can try it.

private LocationClient locationClient;
private static final int LOCATION_UPDATES_INTERVAL = 10000;
private static final int LOCATION_NUM_UPDATES = 5;

public void startLocationUpdate() {
    if (!(locationClient.isConnected() || locationClient.isConnecting())) {
        locationClient.connect(); // Somehow it becomes connected here
        return;
    }
    // Request for location updates
    LocationRequest request = LocationRequest.create();
    request.setInterval(LOCATION_UPDATES_INTERVAL);
    request.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    request.setNumUpdates(LOCATION_NUM_UPDATES);
    locationClient.requestLocationUpdates(request, this);
}

And in the Activity you should implement the following callback

private Location mLastLocation;
    @Override
public void onLocationChanged(Location location) {
    if (location == null) {
        Log.v(TAG, "onLocationChanged: location == null");
        return;
    }

    if (mLastLocation != null &&
            mLastLocation.getLatitude() == location.getLatitude() &&
            mLastLocation.getLongitude() == location.getLongitude()) {
        return;
    }
    LogUtil.i(TAG, "LocationChanged == @" +
            location.getLatitude() + "," + location.getLongitude());
    mLastLocation = location;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!