Search code examples
androidgpslocationalertproximity

in android proximity alert fired even if the proccess who created it terminated?


In my app at some point i create a proximity alert like this:

m_LocationManager.addProximityAlert(lat, lon,  radius, PROXMITY_ALERT_EXPIRATION_TIME, m_PendingIntent);

at some point the procces of my app gets terminated by android, i implement these two methods:

public void onSaveInstanceState(Bundle savedInstanceState)
public void onRestoreInstanceState(Bundle savedInstanceState)

but my alert doesnt fired.., my guess is that i need to move the code that creates the alert to a service.

this is the code for setting the alert:

IntentFilter intentFilter = new IntentFilter("PROX_ALERT_INTENT"); 
    m_NotificationAlertReciever_BroadcastReciever = new NotificationAlertReciever_BroadcastReciever(m_myLocationListener, this);
    registerReceiver(m_NotificationAlertReciever_BroadcastReciever, intentFilter);

    Intent intent = new Intent("PROX_ALERT_INTENT");
    intent.putExtra("lat", lat);
    intent.putExtra("lng", lon);
    intent.putExtra("place", place);

    m_PendingIntent = PendingIntent.getBroadcast(this, -1, intent, PendingIntent.FLAG_CANCEL_CURRENT);   

    this.m_LocationManager.addProximityAlert(lat, lon,  radius, PROXMITY_ALERT_EXPIRATION_TIME, m_PendingIntent);  

can sombody approve that or give other advice.

thanks in advance, Amitos80


Solution

  • The problem is that your BroadcastReceiver is dynamically created from within your activity by using registerReceiver.

    If you want your process to be re-launched when the proximity alert fires then you must declare the receiver in the AndroidManifest like this:

    <receiver android:name=".MyBroadcastReceiver">
      <intent-filter>
        <action android:name="PROX_ALERT_INTENT/>
      </intent-filter>
    </receiver>
    

    Now when the proximity alert is fired, if the process doesn't exist it will be started and MyBroadcastReceiver.onReceive will be invoked.

    Note that using the <receiver> tag like this isn't possible if your receiver is defined as a nested class in your activity (which is often done so the receiver has direct access to methods and data in the activity). With a standalone receiver you're pretty much limited to displaying a notification or starting a service.

    Also note that the PROX_ALERT_INTENT action should really include the application package as a prefix, e.g my.app.PROX_ALERT_INTENT. Not required but it's a convention to keep your actions specific to your app.