Search code examples
androidbroadcastreceiverandroid-serviceandroid-maps-v2locationmanager

Not getting proximity alert "EXITING" even i am out of region


I have created service , which checks proximity of region each second. It fires "Entered the region" correctly. But when i am out of region it continuously giving same message "Entered the region" . I have added proximity in onLocationChanged() method.

Here is a service code:

public class GPSTrackerService extends Service implements LocationListener {

    private Context mContext;
    LocationListener loc;
    // 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
    PendingIntent pendingIntent;
    private BroadcastReceiver mybroadcast;


    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters


    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    @Override
    public void onStart(Intent intent, int startid) {
        this.mContext=getBaseContext();
        getLocation();

    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

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

            // getting network status
            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) {
            e.printStackTrace();
            Toast.makeText(this, "Proximity Service Stopped", Toast.LENGTH_LONG).show();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTrackerService.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;
    }

    /**
     * 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 is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");


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


        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) {

        Toast.makeText(this, "loc changed", Toast.LENGTH_LONG).show();
        Intent proximityIntent = new Intent("in.wptrafficanalyzer.activity.proximity");                 
        pendingIntent= PendingIntent.getBroadcast(mContext, 0, proximityIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
        locationManager.addProximityAlert(31.4668732, 74.2719786,  MIN_DISTANCE_CHANGE_FOR_UPDATES, -1, pendingIntent);             
        IntentFilter filter = new IntentFilter("in.wptrafficanalyzer.activity.proximity");  
        registerReceiver(new ProximityIntentReceiver(), filter);


    }

    @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;
    }

    @Override
    public void onDestroy() {
        try{
            unregisterReceiver(new ProximityIntentReceiver());
        }catch(IllegalArgumentException e){

        }
    }

}

Here is my Broadcat receiver to fire notifications/toast

 @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub


        boolean proximity_entering = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false);

        if(proximity_entering){
            Toast.makeText(context,"Entering the region"  ,Toast.LENGTH_LONG).show();
            notificationTitle="Proximity - Entry";
            notificationContent="Entered the region";
            tickerMessage = "Entered the region";
        }else{
            Toast.makeText(context,"Exiting the region"  ,Toast.LENGTH_LONG).show();


            notificationTitle="Proximity - Exit";
            notificationContent="Exited the region";
            tickerMessage = "Exited the region";

        }

        Intent notificationIntent = new Intent(context,NotificationView.class);
        notificationIntent.putExtra("content", notificationContent );


        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


        NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);


        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
                            .setWhen(System.currentTimeMillis())
                            .setContentText(notificationContent)
                            .setContentTitle(notificationTitle)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setAutoCancel(true)
                            .setTicker(tickerMessage)
                            .setContentIntent(pendingIntent);                           



        nManager.notify(1, notification);


}

}


Solution

  • Hmm, I am not sure...

    First, I would try increasing the variable "MIN_DISTANCE_CHANGE_FOR_UPDATES" to a value greater then 1 (1 means 1 meter, not 10) due to approximate nature of position estimation (no "civilian" provider can give you location up to 1m, not even GPS).

    Then, I would also move the code for adding the Proximity Alert, from OnLocationChanged event, to onStart or some other event or method that fires only once, because in your case, OnLocationChanged is firing whenever you move more then 1 meter resulting in new creation of a Proximity Alert, so you get a bunch of same Proximity Alerts.

    I do not know if this will solve your problems, but you should try, your broadcast receiver code and proximity alert code look just fine to me...