0

I am new to Android and have a problem with adding ProximityAlert with a BroadcastReceiver. I know that this topic has been taken up earlier as well but I am trying to add proximity alert to different locations and I am not sure if what I am trying to do is quite achievable this way or I am just doing it wrong.

Problem : I have tried to implement the code for adding ProximityAlert with a BroadcastReceiver, but its not working some how. Below is the snippet from my code (posted below) requesting all to please have a look and help me out with it.

I have this userLocations list. I am adding Proximity Alert to all the user mentioned location by running a for loop for the list. I only want to add a proximity Alert to the user location if that particular location has not been visited by the user before. I then register the receiver in the addLocationProximity() method, which is called from the onResume() method. I unregisterReceiver the receiver in the onPause() method.

I have also used the onLocationChanged() method to populate a list (which I would be needing for later) based on the same logic which have been used to add the proximity alert.

Please do let me know if any of these steps have not been carried out correctly.

Thanks in advance.

    package com.android.locationmang;

public class ViewAActivity extends ListActivity implements LocationListener{

private static final String PROX_ALERT_INTENT = "com.android.locationmang.PROX_ALERT_INTENT";
private static final long LOCAL_FILTER_DISTANCE = 1200;
public static List<UserLocation> notifiedLocationsList;

public static Location latestLocation;
PendingIntent pendingIntent;
Intent notificationIntent;
private LocationManager locationManager;
List<UserLocations> userLocations;
private IntentFilter filter;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        notifiedLocationsList = new ArrayList<UserLocation>();
        userLocations = getUserLocations(); //Returns a list of user Locations stored by the user on the DB

    filter = new IntentFilter(PROX_ALERT_INTENT);
    }

    private void setUpLocation() {
        locationNotificationReceiver = new LocationNotificationReceiver();

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60, 5, this);

        for (int i = 0; i < userLocation.size(); i++){
            UserLocation userLocation = userLocation.get(i); 
            if(!(userLocation.isComplete())){
                setProximityAlert(userLocation.getLatitude(), 
                        userLocation.getLongitude(), 
                        i+1, 
                        i);
            }
        }
        registerReceiver(locationNotificationReceiver, filter);
    }


    private void setProximityAlert(double lat, double lon, final long eventID, int requestCode){
            // Expiration is 10 Minutes (10mins * 60secs * 1000milliSecs)
            long expiration = 600000;

            Intent intent = new Intent(this, LocationNotificationReceiver.class);
            intent.putExtra(LocationNotificationReceiver.EVENT_ID_INTENT_EXTRA, eventID);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);

            locationManager.addProximityAlert(lat, lon, LOCAL_FILTER_DISTANCE, expiration, pendingIntent);
        }


    @Override
    protected void onResume() {
        super.onResume();

    setUpLocation();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60, 5, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
        unregisterReceiver(locationNotificationReceiver);
    }

    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}


    public boolean userLocationIsWithinGeofence(UserLocation userLocation, Location latestLocation, long localFilterDistance) {
        float[] distanceArray = new float[1];
        Location.distanceBetween(userLocation.getLatitude(), userLocation.getLongitude(), latestLocation.getLatitude(), latestLocation.getLongitude(), userLocation.getAssignedDate(),distanceArray);

        return (distanceArray[0]<localFilterDistance);
    }

    public void onLocationChanged(Location location) {
        if (location != null) {
            latestLocation = location;

            for (UserLocation userLocation : userLocations) {
                if (!(userLocations.isVisited()) && userLocationIsWithinGeofence(userLocation, latestLocation, LOCAL_FILTER_DISTANCE)) {
                    notifiedLocationsList.add(userLocation);
                }
            }
        }
    }
}

Code for BroadcastReceiver

    package com.android.locationmang;

public class LocationNotificationReceiver extends BroadcastReceiver {
    private static final int NOTIFICATION_ID = 1000;
    public static final String EVENT_ID_INTENT_EXTRA = "EventIDIntentExtraKey";

    @SuppressWarnings("deprecation")
    @Override
    public void onReceive(Context context, Intent intent) {
        String key = LocationManager.KEY_PROXIMITY_ENTERING;

        long eventID = intent.getLongExtra(EVENT_ID_INTENT_EXTRA, -1);

        Boolean entering = intent.getBooleanExtra(key, false);
        if (entering) {
            Log.d(getClass().getSimpleName(), "entering");
        }
        else{
            Log.d(getClass().getSimpleName(), "exiting");
        }

        String ns = Context.NOTIFICATION_SERVICE;

        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
        Intent notificationIntent = new Intent(context, MarkAsCompleteActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        Notification notification = createNotification();
        notification.setLatestEventInfo(context, "Proximity Alert!", "You are near your point of interest.", pendingIntent);


        mNotificationManager.notify(NOTIFICATION_ID, notification);
    }

    private Notification createNotification() {
        Notification notification = new Notification();
        notification.icon =  R.drawable.ic_launcher;
        notification.when = System.currentTimeMillis();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_LIGHTS;
        notification.ledARGB = Color.WHITE;
        notification.ledOnMS = 1500;
        notification.ledOffMS = 1500;
        return notification;
    }
}

Thanks and Regards

1 Answers1

0

You are creating a broadcast Intent with an action string, and your <receiver> element does not have the corresponding <intent-filter>. Change:

Intent intent = new Intent(PROX_ALERT_INTENT);

to:

Intent intent = new Intent(this, LocationNotificationReceiver.class);
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Hi @CommonsWare, I have tried to make a few more changes as I wanted to removeProximityAlert() once the user is near the specified location. As I was using the same PendingIntent for all the addresses, it would be hard to identify the particular userLocation that I want to remove from getting proximity alerts so have different intent objects when trying to add up the proximity Alert. I am right in doing that? Or is there another way of doing it? Also, I was using the onLocationChanged() and that worked right before adding the addProximityAlert. Is there a constraint of using the two together? – user1593953 Aug 18 '12 at 16:29
  • @user1593953: "I am right in doing that? Or is there another way of doing it?" -- I have no idea. "Is there a constraint of using the two together?" -- not that I am aware of. – CommonsWare Aug 18 '12 at 16:34
  • Hi @CommonsWare, I have got this working somehow... but now the alerts won't stop... for one location it just goes on n on... is there a parameter somewhere which can control this ? – user1593953 Aug 19 '12 at 16:58
  • Hi @CommonsWare, I am still facing the same issue with the addProximity()... I am not able to get it work when the app is not runnning... I have however decided to go with a service to get rid of this problem... While searching around i saw the locationPoller n i guess its build by you only... If yes can you please let me know with an example how i can use it to compare different locations instead of addProximity? – user1593953 Aug 29 '12 at 20:13
  • @user1593953: `LocationPoller` is designed for "check where we are every hour to check into FourSquare". It is not designed for proximity detection. – CommonsWare Aug 29 '12 at 22:10