Android Proximity alert is not firing - android

I am trying to set up Proximity alert below is my code but Its not firing at all
Intent intent = new Intent(ACTION_PROXIMITY_ALERT);
pendingIntent = PendingIntent.getBroadcast(GMapsActivity.this, 0, intent, 0);
locationManager.addProximityAlert(mNavigationDatas.get(CURRENT_INDEX).startCordinates.latitude,
mNavigationDatas.get(CURRENT_INDEX).startCordinates.longitude, 100f, -1, pendingIntent);
IntentFilter filter = new IntentFilter(ACTION_PROXIMITY_ALERT);
registerReceiver(new ProximityBroadcastListener(), filter);
Permissions are as follows
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I am sending Mock location to test on real device Android v4.1.2 mock location follows correct path but broadcast listener is not called
public class ProximityBroadcastListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final String key = LocationManager.KEY_PROXIMITY_ENTERING;
final Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
String instruction = mNavigationDatas.get(CURRENT_INDEX).drivingInstuctions;
instruction = instruction.replaceAll("<[^>]*>", "");
Log.e("", instruction);
tts.speak(instruction, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(context, "entering", Toast.LENGTH_SHORT).show();
} else {
locationManager.removeProximityAlert(pendingIntent);
CURRENT_INDEX++;
locationManager.addProximityAlert(mNavigationDatas.get(CURRENT_INDEX).startCordinates.latitude,
mNavigationDatas.get(CURRENT_INDEX).startCordinates.longitude, 100f, -1, pendingIntent);
Toast.makeText(context, "exiting", Toast.LENGTH_SHORT).show();
}
}
Thanks
Saurabh

Firstly, I would suggest registering the BroadcastReceiver before adding the proximity alert. If your device is already at that location, it may fire the intent before your receiver is ready to listen for it.
You may also want to check that your receiver is registered correctly by manually firing the PendingIntent, for instance through the AlarmManager, a notification or simply by pressing a button.
If none of this works, consider experimenting with a physical device as there are some problems with location events on the emulator. For instance, due to a bug in the emulator, the time offset in incoming locations is set to midnight, so your location criteria will likely not match it.

Related

Proximity Alert not triggering

I'm having some trouble getting my proximity alert to work on my Android app that's running on an Emulator. Basically the proximity alert should start an activity that will (for now) print to the log, however when a desired location is set for the alert, and the emulator's location is set at that particular location, nothing happens. Here is the code for the proximity alert:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Intent intent = new Intent(MY_PROXIMITY_ALERT);
PendingIntent proxIntent = PendingIntent.getActivity(MapActivity.this, 0, intent, 0);
lm.addProximityAlert(latlng.latitude, latlng.longitude, 100, -1, proxIntent);
Now MY_PROXIMITY_ALERT is declared in the manifest as stated below:
<receiver android:name=".myLocationReceiver">
<intent-filter>
<action android:name="PROXIMITY_ALERT"/>
</intent-filter>
</receiver>
And here is my code for myLocationReceiver
public class myLocationReceiver extends BroadcastReceiver{
private static final String TAG = "myLocationReceiver";
#Override
public void onReceive(Context context, Intent intent) {
final String key = LocationManager.KEY_PROXIMITY_ENTERING;
final Boolean entering = intent.getBooleanExtra(key, false);
if(entering) {
Log.d(TAG, "onReceive: Entering proximity of location");
}
}
}
I believe my problem has something to do with the Intent or PendingIntent object but I'm not entirely sure. Also I have heard that usually the GPS will take about a minute to actually register the proximity, but I still do not get a log message even after some time.
Thanks!
You've created an Intent with action MY_PROXIMITY_ALERT and then used PendingIntent.getActivity() to get a PendingIntent to pass to the LocationManager. When the proximity conditions are satisfied, LocationManager will try to start an Activity that is listening for action MY_PROXIMITY_ALERT.
Intent intent = new Intent(MY_PROXIMITY_ALERT);
PendingIntent proxIntent = PendingIntent.getActivity(MapActivity.this, 0, intent, 0);
In your manifest, you've declared a BroadcastReceiver that is listening for action MY_PROXIMITY_ALERT. This won't work.
Since you want the proximity alert to trigger a BroadcastReceiver, you need to get the PendingIntent like this:
Intent intent = new Intent(MY_PROXIMITY_ALERT);
PendingIntent proxIntent = PendingIntent.getBroadcast(MapActivity.this, 0, intent, 0);
Personally, I think it would be better to use an "explicit" Intent instead of an "implicit" Intent. In that case you would do it like this:
Intent intent = new Intent(MapActivity.this, myLocationReceiver.class);
PendingIntent proxIntent = PendingIntent.getBroadcast(MapActivity.this, 0, intent, 0);
You don't need to use the ACTION in the Intent.
Using an "explicit" Intent tells Android exactly what component (class) to launch. If you use an "implicit" Intent, Android has to search for components that advertise that they can handle certain ACTIONs.

addProximityAlert not working

I'm trying to use addProximityAlert. I've followed the tutorial from this site http://myandroidtuts.blogspot.dk/2012/10/proximity-alerts.html.
I've also tried other tutorials but I couldn't get them to work either.
This is my code for creating the proximity alert:
double lat = 55.659890;
double longi = 12.591188;
float radius = 3000;
lm = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Intent intent = new Intent("dk.itu.percom.tourguide.android.ProximityAlert");
long expire = -1;
proximityIntent = PendingIntent.getBroadcast(getApplicationContext(), -1, intent, 0);
lm.addProximityAlert(lat, longi, radius, expire, proximityIntent);
This is my receiver:
public class ProximityIntentReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String k=LocationManager.KEY_PROXIMITY_ENTERING;
boolean state=intent.getBooleanExtra(k, false);
if(state){
Toast.makeText(context, "Welcome to my Area", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "Thank you for visiting my Area,come back again!!",Toast.LENGTH_LONG).show();
}
}
}
And my manifest:
<receiver android:name="ProximityIntentReceiver"
android:exported="false" >
<intent-filter>
<action android:name="dk.itu.percom.tourguide.android.ProximityAlert" />
</intent-filter>
</receiver>
And I've added the permissions
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
I have also tried to add the receiver with
IntentFilter filter = new IntentFilter("dk.itu.percom.tourguide.android.ProximityAlert");
registerReceiver(new ProximityIntentReceiver(), filter);
But that doesn't work either. Somewhere I also read that using -1 for expiration doesn't work with 4.3 and you instead should use a very high number, but no luck with that either.
Does anybody know what the problem could be?
If you read the Android officiel doc (here) you'll find this sentence "Due to the approximate nature of position estimation, if the device passes through the given area briefly, it is possible that no Intent will be fired"
what is that mean? it means when you are testing your app on the AVD and u send a gps coordinates(latitude, longitude) from the DDMS to AVD its really hard to simulate the real aspect of a gps, (because in the first place u pick some point to be your proximPoint and just after that you choose anthor point very far from the proximPoint to see if its work) and thats not what it's happing with a real device.
so the solution is to test your app on a real device or with the DDMS try to change the coordiantes very slowly until you are in the zone wanted.

Android: how to set a proximity alert to fire only when exiting or only when entering the location

I am developing a ToDo app with reminders(by time and by location) and the thing is I give the user the option to choose if he wants the reminder by location to alert when he is entering the location or when he exits the location.
how can i do that??
I know about the KEY_PROXIMITY_ENTERING but I dont know how to use it
Please help...
thanx in advance
The KEY_PROXIMITY_ENTERING is usually used to determine whether the device is entering or exiting.
You should first register to the LocationManager
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Intent intent = new Intent(Constants.ACTION_PROXIMITY_ALERT);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
locationManager.addProximityAlert(location.getLatitude(),
location.getLongitude(), location.getRadius(), -1, pendingIntent);
The PendingIntent will be used to generate an Intent to fire when entry to or exit from the alert region is detected.
You should define a broadcast receiver to receive the broadcast sent from LocationManager:
public class YourReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final String key = LocationManager.KEY_PROXIMITY_ENTERING;
final Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
Toast.makeText(context, "entering", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "exiting", Toast.LENGTH_SHORT).show();
}
}
}
Then register the receiver in your manifest.
<receiver android:name="yourpackage.YourReceiver " >
<intent-filter>
<action android:name="ACTION_PROXIMITY_ALERT" />
</intent-filter>
</receiver>
You can find a good example here:
http://www.java2s.com/Code/Android/Core-Class/ProximityAlertDemo.htm

Android Proximity Alerts on Galaxy Nexus with Android 4.1.1 - does it really work?

I would like to use Android's LocationManager and the addProximityAlert method to setup proximity alerts. For this, I've created a small application that shows a crosshair on top of a map, plus a text field for the proximity alert name and a button to trigger the addition of the alert.
Unfortunately, the BroadcastReceiver that should receive the proximity alerts is not triggered. I've tested the intent alone (not wrapped via a PendingIntent) and that works. Also, I see that once a proximity alert is set, the GPS / location icon appears in the notification bar.
I've found information about proximity alerts a bit confusing - some are telling the alerts cannot be used if the activity is no longer in the foreground. I think it should work, so I assume something else is wrong.
1 Adding a Proximity alert
GeoPoint geo = mapView.getMapCenter();
Toast.makeText(this, geo.toString(), Toast.LENGTH_LONG).show();
Log.d("demo", "Current center location is: " + geo);
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, getLocationAlertIntent(), 0);
locationManager.addProximityAlert(geo.getLatitudeE6()/1E6, geo.getLongitudeE6()/1E6, 1000f, 8*60*60*1000, pIntent);
The intent itself is here:
private Intent getLocationAlertIntent()
{
Intent intent = new Intent("com.hybris.proxi.LOCATION_ALERT");
intent.putExtra("date", new Date().toString());
intent.putExtra("name", locationName.getEditableText().toString());
return intent;
}
I created a receiver which is supposed to receive the location alerts, registered in AndroidManifest.xml:
<receiver android:name=".LocationAlertReceiver">
<intent-filter>
<action android:name="com.hybris.proxi.LOCATION_ALERT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
The implementation itself is hopefully straightforward. It is supposed to show a notification (and I checked that via directly sending an intent with a test button).
public class LocationAlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context ctx, Intent intent) {
Log.d("demo", "Received Intent!");
String dateString = intent.getStringExtra("date");
String locationName = intent.getStringExtra("name");
boolean isEntering = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false);
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(ctx)
.setContentTitle("LocAlert: " + locationName)
.setContentText(dateString + "|enter: " + isEntering)
.setSmallIcon(R.drawable.ic_stat_loc_notification)
.build();
notificationManager.notify(randomInteger(), notification);
}
private int randomInteger()
{
Random rand = new Random(System.currentTimeMillis());
return rand.nextInt(1000);
}
A few things that I am not 100% sure of, maybe this triggers something in you:
I assume it is OK to register a proximity alert using a pending intent like I do and the Activity that created the proximity alert can later be closed.
Converting from the Map via getCenter returns a GeoPoint with lat/lon as int values. I thnk I am correctly converting them the the double values expected by addProximityAlert by dividing by 1E6
The distance from the center is relatively large - 1000m - I assume that is a nice value.
Examples that I've found online used broadcast receivers registered programmatically. this is not what I want to do. but the book Android 4 Profession Dev by Reto Meier mentions that registering the broadcast receiver in xml is also fine.
Any help greatly appreciated!!
I ran into the same issue. Setting target class of the intent explicitly helped in my case. In your case it should look the following:
private Intent getLocationAlertIntent()
{
Intent intent = new Intent(context, LocationAlertReceiver.class);
intent.setAction("com.hybris.proxi.LOCATION_ALERT"); //not sure if this is needed
intent.putExtra("date", new Date().toString());
intent.putExtra("name", locationName.getEditableText().toString());
return intent;
}

addProximityAlert and BroadcastReceivers

I am currently working on a map app that has points of interest built into it.
These points are supposed to be announced to the user by means of a proximity alert trigger.
Here is the addproximityAlert() code that I'm using
loc.addProximityAlert(lat, longe, radius, -1, PendingIntent.getActivity(
c, 0, new Intent().putExtra(loc_name, loc_name), flag));
The idea is that once the alert fires an alert dialog pops up with a short blurb about the site with the option to either close the alert or get more info(uses WebView).
Thus far I have no run-time or compile-time errors but as I approach each site, nothing happens.
My theory on why nothing happens is that either;
1) I haven't used the PendingIntent correctly, or
2) I haven't set up the BroadcastReceiver correctly
Here is the XML code for the BroadcastRecevier,
<receiver android:name=".ProxyAlertReceiver" >
<intent-filter>
<action android:name="entering" />
</intent-filter>
</receiver>
My current plan to fix this issue is to modify the PendingIntent to use a new Intent like this;
...new Intent(myContext, ProxyAlertReceiver.class)...
and see if I get any results.
Opinions and advice on my issue would be greatly appreciated!
Have you tried PendingIntent.getBroadcast(...)?
Intent locationReachedIntent = new Intent("entering");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1234,
locationReachedIntent, 0);
locationManager.addProximityAlert(longitude, latitude, radius, -1, pendingIntent);
I have the above code working in my application.
Use This
Intent locationIntent = new Intent();
Bundle extras= new Bundle();
extras.putString("loc_name",loc_name);
locationIntent.putExtras(extras);
PendingIntent pendingIntent= new PendingIntent.getActivity(this,0,locationIntent,0);
loc.addProximityAlert(lat, longe, radius, -1, pendingIntent, flag));
I assume your loc_name is a string. This will work.
Implementing a proximity alert depends on more than just calling the addProximity method on a Location Manager.
You must also:
Create a receiver class which will fire when alert is triggered and will receive a status (entering or exiting) and the action name*;
public class ProximityReceiver extends BroadcastReceiver {
public String TAG ="ProxReceiver";
#Override
public void onReceive(Context context, Intent intent) {
/* your code here - sample below */
final String key = LocationManager.KEY_PROXIMITY_ENTERING;
final Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
Toast.makeText(context, "LocationReminderReceiver entering", Toast.LENGTH_SHORT).show();
Log.v(TAG, "Poi entering");
} else {
Toast.makeText(context, "LocationReminderReceiver exiting", Toast.LENGTH_SHORT).show();
Log.v(TAG, "Poi exiting");
}
Log.v(TAG,"Poi receive intent["+intent.toString()+"]");
Bundle extras = intent.getExtras();
// debugging only
int counterExtras = extras.size();
if (extras != null) {
for (String key : extras.keySet()) {
Object value = extras.get(key);
Log.d(TAG, "Prox Poi extra "+String.format("key[%s] value[%s] class[%s] count[%s]", key,
value.toString(), value.getClass().getName(), String.valueOf(counterExtras)));
}
} else {
Log.v(TAG, "Prox Poi extra empty");
}
}
}
Declare this receiver in your Manifest file;
<receiver android:name=".ProximityReceiver" >
<intent-filter>
<action android:name="my" />
</intent-filter>
</receiver>
Register (associate your pending intents to) this receiver, adding proximity alert(s). Only register your receiver ONCE in your code. If one registers a receiver multiple times, it will fire once for every receiver instance (you reach a POI, which registers a pending intent called "my". **
// create proximity alert
Intent locationIntent = new Intent("my");
ProximityReceiver proximityReceiver = new ProximityReceiver();
PendingIntent pendingIntent = PendingIntent.getBroadcast(mapView.getContext(), <some identifying text>,
locationIntent, 0);
loc.addProximityAlert(lat, longe, radius, -1, PendingIntent.getActivity(
c, 0, new Intent().putExtra(loc_name, loc_name), flag));
IntentFilter filter = new IntentFilter("my");
context.registerReceiver(proximityReceiver, filter);
Where context can be this if running in same activity.
Unless you want to keep on receiving alerts even when in background (or even terminated), you must implement removal and re-creation of proximity alerts in your onPause and onResume methods, like this SO question (jump to the end of the question).
note * In this example, "my" will be the action name (see Intent declaration) for an action and will be passed along with the intent AND a bundle of extras containing, at least, the key entering (LocationManager.KEY_PROXIMITY_ENTERING) with boolean value, which gives you the state of the alert, if one is entering (1) or exiting (0) the proximity radius.
note ** If you have registered the receiver for "my" multiple times, it will fire multiple times for every proximity alert event that calls an intent named "my".

Categories

Resources