Proximity Alert In Android

What are Proximity Alerts?

—- Till date we always use alert system to give alert on specific time i.e. on Birthday’s, Anniversary etc.. But what if we don’t know exact time but we know place consider example that you want to fix your glasses when you go nearby your glass repair store. So you exactly don’t know when you are going there but whenever you go you want a reminder that you are nearby your glass store & repair your glass. For these purpose proximity alerts are used.To achieve this we want help from LocationManager class & we need to create a BroadcastReceiver to recive proximity event & also we need to create a pending event.

I am considering you are aware of LocationManager, BroadcastReceiver & Pending Intent.

To create proximity alert we need latitude & longitude of the location for which you want to create alert, then redius (It will create a circle around given lat & lon of this redius & whenever we enter or exit this circle it will give alert) & pending Intent & expire time (this alert will active only for this given miliesconds if you want unlimited time simply keep it to -1)

Lets go for some code instead of theory

1) Main Layout (main.xml)— Here I am creating a layout which has two textbox to enter latitude & longitude & a button to add proximity alert.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
              android:id="@+id/point_latitude"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_marginLeft="25dip"
              android:layout_marginRight="25dip"
              android:hint="Latitude"
       />

       <EditText
              android:id="@+id/point_longitude"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:layout_marginLeft="25dip"
              android:layout_marginRight="25dip"
              android:hint="Longitude"
       />
       <Button
              android:id="@+id/add_alert_button"
              android:text="Add Alert"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
       />

</LinearLayout>

2) Main Activity ProximityAlertActivity.java

public class ProximityAlertActivity extends Activity {
       private static final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 1; // in Meters
       private static final long MINIMUM_TIME_BETWEEN_UPDATE = 1000; // in Milliseconds
       private static final long POINT_RADIUS = 100; // in Meters
       private static final long PROX_ALERT_EXPIRATION = -1; // It will never expire
       private static final String PROX_ALERT_INTENT = "com.androidmyway.demo.ProximityAlert";
private LocationManager locationManager;
private EditText latitudeEditText;
       private EditText longitudeEditText;
       private Button addAlertButton;

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

              locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

              latitudeEditText = (EditText) findViewById(R.id.point_latitude);
              longitudeEditText = (EditText) findViewById(R.id.point_longitude);
              addAlertButton = (Button) findViewById(R.id.add_alert_button);

              addAlertButton.setOnClickListener(new OnClickListener() {
                     public void onClick(View v) {
                            addProximityAlert();
                     }
              });

       }

       private void addProximityAlert() {
              double latitude = Double.parseDouble(latitudeEditText.getText().toString());
              double longitude = Double.parseDouble(longitudeEditText.getText().toString());
              Intent intent = new Intent(PROX_ALERT_INTENT);
              PendingIntent proximityIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
locationManager.addProximityAlert(
                     latitude, // the latitude of the central point of the alert region
                     longitude, // the longitude of the central point of the alert region
                     POINT_RADIUS, // the radius of the central point of the alert region, in meters
                     PROX_ALERT_EXPIRATION, // time for this proximity alert, in milliseconds, or -1 to indicate no                           expiration
                     proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected
              );

              IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
              registerReceiver(new ProximityIntentReceiver(), filter);
              Toast.makeText(getApplicationContext(),"Alert Added",Toast.LENGTH_SHORT).show();
       }
}

3)ProximityReceiver.java

public class ProximityIntentReceiver extends BroadcastReceiver {
       private static final int NOTIFICATION_ID = 1000;

       @Override
       public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
                     Log.d(getClass().getSimpleName(), "entering");
              }else {
                     Log.d(getClass().getSimpleName(), "exiting");
              }
              NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

              Intent notificationIntent = new Intent(context, ProximityAlertActivity.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);

              notificationManager.notify(NOTIFICATION_ID, notification);
      }

       private Notification createNotification() {
              Notification notification = new Notification();
notification.icon = R.drawable.ic_menu_notifications;
              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_LIGHTS;
notification.ledARGB = Color.WHITE;
              notification.ledOnMS = 1500;
              notification.ledOffMS = 1500;
              return notification;
        }
}

You need to add following uses permission in your menifest file

       <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
       <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
       <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
       <uses-permission android:name="android.permission.VIBRATE" />

This article is based on  Developing Proximity Alerts for Mobile Applications using the Android Platform

You can download code from https://github.com/sandipmjadhav/Proximity-Alert

Thank You

26 thoughts on “Proximity Alert In Android

      • ok,
        Here entering means you are near by ur location within the range of 100 meters
        private static final long POINT_RADIUS = 100; // in Meters
        Think like this will create a circle around your danger of given radius & when you enter in this circle it will give notification it means you are near your danger or you are nearly away from your danger by approximate distance of radius

      • i putted 2 meters in my app, i have danger in : -82 (longitude ) and 28 latitude i tried in DDMS : -81 (longitude) and 28 (latitude ) i didn’t have a notification 😦 but when i putted -82 and 28 i had in logcat “entering” and i had the notification !!! plz help me i’m exhausted 😦

      • Create a custom class extend it to AlertDialog and create only one object so that you can check if dialog is opened or not & if open close that & open new…

      • it doesn’t work : i declare a variable isShown and test if there’s a dialog… also i have a button “ok” on the dialog ( onclick (..) dialog.dismiss ) . i tried to remove all proximity alerts and add them after every onLocationChanged ==> doesn’t work 😦 this is my code :
        private void registerIntents() {
        bd.open();
        List maListe =new ArrayList();
        maListe=bd.getAllDangers();
        bd.close();
        for(int i = 0; i < maListe.size(); i++)
        {

        String msg = maListe.get(i).toString();
        setProximityAlert(maListe.get(i).getlati(),
        maListe.get(i).getlongi(),
        i+1,
        i,msg);

        }
        }

        /** Configure a proximity alert */
        private void setProximityAlert(double lat, double lon, final long eventID, int requestCode, String text)
        {

        String intentAction = PROX_ALERT_INTENT + eventID + System.currentTimeMillis();
        // 100 meter radius
        float radius = 100f;

        long expiration = -1;
        Intent intent = new Intent(intentAction);
        //puts the text information
        intent.putExtra(ProximityAlert.TEXT_INTENT_EXTRA, text);

        PendingIntent proximityIntent = PendingIntent.getBroadcast(
        this, requestCode, intent,
        PendingIntent.FLAG_CANCEL_CURRENT);

        LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        locManager.addProximityAlert(lat, lon, radius, expiration, proximityIntent);
        IntentFilter filter = new IntentFilter(intentAction);
        registerReceiver(new ProximityAlert(), filter);

        }

        private void removeProximityAlert( final long eventID, int requestCode)
        {

        String intentAction = PROX_ALERT_INTENT + eventID + System.currentTimeMillis();

        Intent intent = new Intent(intentAction);

        PendingIntent proximityIntent = PendingIntent.getBroadcast(
        this, requestCode, intent,
        PendingIntent.FLAG_ONE_SHOT);

        LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        locManager.removeProximityAlert( proximityIntent);

        }

        private void removeIntents() {
        bd.open();
        List maListe =new ArrayList();
        maListe=bd.getAllDangers();
        bd.close();
        for(int i = 0; i < maListe.size(); i++)
        {

        removeProximityAlert(i+1,
        i);

        }
        }

      • Do one thing
        1)Create a class and extend it to application
        class abc extend Application{
        static boolean isMsgVisible = false;
        }
        2) When you show alertbox make this variable true
        abc.isMsgVisible = true;
        3) When you dismiss alertbox make this variable false.

  1. hi help me out ..
    i am on a project that uses multiple proximity alerts ..
    in a simple way i have n number of POI(point of interest) when i reach particular POI i should send a sms to predifined no that will be stored in DATABASE….
    How to implement this one give me an idea….im really exhausted by trying this one …

    • Instead of creating notification in “ProximityIntentReceiver” you need to access database and get those mobile no and send sms to them.
      What exactly you are trying and where you are having problems in it??

      • First for all thanks for your reply…

        can i have a simple example that uses multiple proximity alerts …. when i use single proximity alert all things works fine but when i use proximity alerts more than once program will not run as previous … i used multiple proximity with separate UNIQUE ID for individual intents …

        This is how i am using multiple proximity alerts..

        IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
        registerReceiver(new ReportReciever(), filter);

        Intent mIntent = new Intent(PROX_ALERT_INTENT);
        mIntent.putExtra(“abhishek”, 3);

        PendingIntent proxIntent = PendingIntent.getBroadcast(this, 0, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        proxIntent.cancel();
        locationManager.addProximityAlert(13.060422,80.249583, 50, -1, proxIntent);

        IntentFilter filter2 = new IntentFilter(PROX_ALERT_INTENT+2);
        registerReceiver(new ReportReciever(), filter2);

        Intent mIntent2 = new Intent(PROX_ALERT_INTENT+2);
        mIntent.putExtra(“abhishek”, 2);

        PendingIntent proxIntent2 = PendingIntent.getBroadcast(this, 0, mIntent2, PendingIntent.FLAG_CANCEL_CURRENT);
        proxIntent2.cancel();
        locationManager.addProximityAlert(12.914993,77.541223, 50, -1, proxIntent2);

        waiting for your reply…

  2. @Abhishek — Let me explain you what I have done to add multiple alerts
    In manifest — registered a service

    Service code as follows

    public class myProximityService extends Service{

    @Override
    public void onCreate() {
    // TODO Auto-generated method stub
    //Toast.makeText(this, “MyAlarmService.onCreate()”, Toast.LENGTH_LONG).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    Toast.makeText(this, “MyAlarmService.onBind()”, Toast.LENGTH_LONG).show();
    return null;
    }

    @Override
    public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    Toast.makeText(this, “MyAlarmService.onDestroy()”, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStart(Intent intent, int startId) {
    // TODO Auto-generated method stub
    String key = LocationManager.KEY_PROXIMITY_ENTERING;

    Boolean entering = intent.getBooleanExtra(key, false);

    if (entering) {
    Log.d(getClass().getSimpleName(), “entering”);
    GlobalValues.isProximityAlert = true;
    GlobalValues.proximityTitle = intent.getStringExtra(“title”);
    GlobalValues.proximityMessage = intent.getStringExtra(“message”);

    NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(getApplicationContext(), ReminderHome.class);

    notificationIntent.putExtra(“EventID”, intent.getIntExtra(“EventID”,0));
    notificationIntent.putExtra(“title”,intent.getStringExtra(“title”));;
    notificationIntent.putExtra(“message”,intent.getStringExtra(“message”));

    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    Notification notification = createNotification();
    notification.setLatestEventInfo(getApplicationContext(), intent.getStringExtra(“title”), intent.getStringExtra(“message”), pendingIntent);

    notificationManager.notify((int) startId, notification);
    }else {
    Log.d(getClass().getSimpleName(), “exiting”);
    }
    }

    @Override
    public boolean onUnbind(Intent intent) {
    // TODO Auto-generated method stub
    Toast.makeText(this, “MyAlarmService.onUnbind()”, Toast.LENGTH_LONG).show();
    return super.onUnbind(intent);
    }

    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_LIGHTS;

    notification.ledARGB = Color.WHITE;
    notification.ledOnMS = 1500;
    notification.ledOffMS = 1500;

    return notification;
    }

    }

    Reminder is added as below.

    note:– Before calling below function i save all the details in the database.
    private void setProximityAlert(double lat, double lon, int requestCode, String title, String msg ){
    // 100 meter radius
    float radius = 100f;

    long expiration = -1;

    LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Intent intent = new Intent(getApplicationContext(), myProximityService.class);

    intent.putExtra(“EventID”, requestCode);
    intent.putExtra(“title”, title);
    intent.putExtra(“message”, msg);

    PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), (int)requestCode, intent,Intent.FLAG_ACTIVITY_NEW_TASK);

    locManager.addProximityAlert(lat, lon, radius, expiration, pendingIntent);
    }

    This is what I have done.
    Working on a clean copy of multiple proximity alert demo.
    Till then you can try out with these things
    Thank You.

  3. Its great that you spend so much time helping others out! Thanks for that! I have been using your code to create a proximity alert for a map marker, and it works great, exact same code that you use basically. but if I have 7 markers, how can I create an alert for all of these? I am trying to keep it simple as possible. All of my map markers are stored in an array so I am accessing the lat and long of each via this array index. Any suggestions on how to add to what you already gave us to create multiple separate alerts? thank you!!!

    • Hi
      M using your code…But it works only when I run my application…It should run when am entering in that specific place…

  4. Hi sandip,

    could you upload your source code for multiple proximity alert..?

    Nice tutorial,but my requirements is totally i have five marker in Google map with 10 meter radius,if i enter any radius i want to show notification.actually i did that but last marker only show the notification how to fix the multiple notification,please help me this is my mail id (jeeva2k10@gmail.com).

    i am waiting for your query.

    thanks.

  5. Unable to get alert 😦
    I’m using same code and tried on android 2.2, 4.1.2 and 4.2.2(Emulator) butt it doesn’t work for me.
    Please help me out.
    Looking for your response.

  6. hey hi.. i tried your code. But didnt get any notification. The toast shows distance as an emty space when i reach the POI. but it doesnt fire an alert. What should i do?

Leave a comment