onLocationChanged如何运作?

时间:2014-09-15 09:59:32

标签: android google-maps geolocation

在我的应用程序中,我有一个按钮,开始计算用户在同一位置的时间。我希望应用程序停止计时器计数,如果用户从他开始的区域出去,所以我做了一个给我当前位置的课程(LAT,LONG,PLACE NAME),我不知道如何使用“onLocationChanged “我应该用吗?或其他我需要的东西?

public class MapCurrentPlace extends Service implements LocationListener {


    private final Context mContext;

    public static final String MY_TEMP = "sharedFile"; 

    SharedPreferences setting;
    SharedPreferences.Editor editor;


    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    String placeName = "";


    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 500; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;



    public MapCurrentPlace(Context context) {
        this.mContext = context;
        getLocation();

    }



    public String getPlaceName(){

            Geocoder gc = new Geocoder(mContext);
        try {
                List<Address>  list = gc.getFromLocation(latitude, longitude, 1);
                 if(list.size()>0){
                String city = list.get(0).getLocality();
                String street = list.get(0).getAddressLine(0);
                placeName = city+", "+street+"";        
    }
            } catch (IOException e) {
            placeName = "";         
            e.printStackTrace();
            }



        return placeName;
    }


    public Location getLocation() {

        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(Context.LOCATION_SERVICE);
                        // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                      // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);








            if (!isGPSEnabled) {
                // no network provider is enabled

                 this.canGetLocation = false;
                return null;

            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {

                    locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,0, this);

                    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,0, this);

                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (location != null) {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();

                            }
                        }
                    }
                }
            }

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

        }
        return location;
    }


    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(MapCurrentPlace.this);
        }     
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    public boolean getIsNetworkEnabled() {

        return this.isNetworkEnabled;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS OFF");

        // Setting Dialog Message
        alertDialog.setMessage("Allow GPS");

        // On pressing Settings button
        alertDialog.setPositiveButton("SETTING", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @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 intent) {
        // TODO Auto-generated method stub
        return null;
    }



}

3 个答案:

答案 0 :(得分:0)

locationManager.getLastKnownLocation 

这个返回上次知道的位置修复。如果没有应用程序请求位置一段时间,这可能有点旧。 每次更改设备位置时都会触发位置更新。

所以它取决于你使用什么。如果您想获得最新位置,请使用位置更新。但请记住,位置更新了电池。

您也可以查看Geofences:http://developer.android.com/training/location/geofencing.html

答案 1 :(得分:0)

当前位置发生变化时,将调用onLocationChanged方法。这是一个调用的默认方法,因为您已实现了LocationListener。 我不知道你是如何实现计时器的(也许是AsyncTask,所以你的应用程序也可以做其他的事情 - http://developer.android.com/reference/android/os/AsyncTask.html),但是然后在OnLocationChanged方法中添加一些调用你的计时器变量来停止。

答案 2 :(得分:0)

当设备从您设备的最后一个相关位置(即自上次触发事件以来)移动OnLocationChanged minDistance参数时,

OnLocationChanged将会触发。

当然,触发率还考虑了minTime参数,该参数应该用于防止呼叫饱和,从而节省电池/数据使用量(例如汽车行驶速度太快,不能用于你的minDistance)。

正如您现在所拥有的那样(您为通话提供了内联0),如果最近的// The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 30; //30 meters //... //at some point while your service/activity is running locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this); //... @Override public void onLocationChanged(Location currentLocation) { //triggered when System asserts a 30 meter variation from last relevant location doMyStuff(); } 数据是对您的方案的相关更改,则需要手动检查。< / p>

使用该参数会更加透明,因为系统会尝试使其与硬件无关并节省电池电量。您的样板代码中已经有 MIN_DISTANCE_CHANGE_FOR_UPDATES ,只需将其作为参数而不是'0'添加,并将其设置为您需要的米数:

Location

旁注:请记住,大多数GPS硬件都存在非常精细的位置问题,特别是在10米以下。

您还可以将值保持为0,以硬件更新自身的粒度接收更新,并手动执行检查 - 只需使用事件提供的Location lastRelevantLocation; @Override public void onLocationChanged(Location currentLocation) { // called when the listener is notified with a location update from the GPS // hardware update rate might call this more than your CPU should handle if(checkOutsidePerimeter(location)){ lastRelevantLocation = currentLocation; doMyStuff(); } } 参数并自行检查以确定哪个几乎是一个地理围栏检查:

{{1}}

如果你想密切关注粒度,请记住minTime。