Unable to display notification when entering GeoFence in Android
Asked Answered
L

3

4

I am working on GeoFencing in Android and I am stuck at one point. My task is to show notification to user when he enters/exits a Geofence area defined by me.

Here is my code:

Activity class

public class TestMapActivity extends FragmentActivity implements    
    OnMarkerDragListener,ConnectionCallbacks, OnConnectionFailedListener,OnAddGeofencesResultListener {

private static GoogleMap map;
private LocationClient mLocationClient;
private PendingIntent mGeofencePendingIntent;
private SimpleGeoFence fence;
private List<Geofence> mGeoList;
private LocationRequest localRequest;
private GeofenceReceiver mBroadcastReceiver;
private IntentFilter mIntentFilter;

@Override
protected void onCreate(Bundle saveInstance)
{
        super.onCreate(saveInstance);
        setContentView(R.layout.activity_map);
        map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        map.setOnMarkerDragListener(this);
        CameraPosition INIT =
        new CameraPosition.Builder()
        .target(new LatLng(19.0222, 72.8666))
        .zoom(17.5F)
        .bearing(300F) // orientation
        .tilt( 50F) // viewing angle
        .build();
         map.moveCamera( CameraUpdateFactory.newCameraPosition(INIT) );

 }


   @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main, menu);
        return true;
    }

 @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {

        switch (item.getItemId())
        {
            case R.id.add_fence:

            Toast.makeText(TestMapActivity.this, "Add fence is Selected", Toast.LENGTH_LONG).show();

            fence= new SimpleGeoFence();
            fence.toGeofence();
            addMarkerForFence(fence);
            addIntentForFence();
            return true;
            default:
                 return super.onOptionsItemSelected(item);
        }
    }

     public void addMarkerForFence(SimpleGeoFence fence){
     if(fence == null){
         // display an error message and return
        return;
     }


     //Instantiates a new CircleOptions object +  center/radius
     CircleOptions circleOptions = new CircleOptions()
       .center( new LatLng(19.0216, 72.8646 ))
       .radius( 500 )
       .fillColor(0x40ff0000)
       .strokeColor(Color.TRANSPARENT)
       .strokeWidth(2);

     map.addCircle(circleOptions);

     map.addMarker( new MarkerOptions()
       .position( new LatLng(19.0216, 72.8646) )
       .title("Fence " +fence.getId())
       .snippet("Radius: " +fence.getRadius()) ).showInfoWindow();

     // Get back the mutable Circle
     Circle circle = map.addCircle(circleOptions);

 }

     public void addIntentForFence()
 {

     Geofence geoFence= fence.toGeofence();
     mGeoList = new ArrayList<Geofence>();
     mGeoList.add(geoFence);

     mLocationClient = new LocationClient(this, this, this);
     mLocationClient.connect();

    }

   @Override
public void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub

    mGeofencePendingIntent = createRequestPendingIntent(); 

    localRequest = LocationRequest.create();
    localRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    localRequest.setInterval(5000);

    mLocationClient.addGeofences(mGeoList, mGeofencePendingIntent , this);  
}

    private PendingIntent createRequestPendingIntent() {

    if (null != mGeofencePendingIntent) {

        return mGeofencePendingIntent;

    } else {


        Intent intent = new Intent("com.example.ACTION_RECEIVE_GEOFENCE");
        System.out.println("Intent" +intent);
        //sendBroadcast(intent);
        return PendingIntent.getBroadcast(
                getApplicationContext(),
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }
}
} //end oncreate

GeofenceReceiver class

  public class GeofenceReceiver extends BroadcastReceiver
  {
         public Context context;
         Intent broadcastIntent = new Intent();

          @Override
      public void onReceive(Context context, Intent intent) {

           // TODO Auto-generated method stub

             this.context = context;
              broadcastIntent.addCategory("com.example.CATEGORY_LOCATION_SERVICES");        
              String action= intent.getAction();

               if (LocationClient.hasError(intent)) {
                       //do something
                } 
               else 
                {
               handleEnterExit(intent);
                 }
           }

         private void handleEnterExit(Intent intent) {

             int transition = LocationClient.getGeofenceTransition(intent);

              System.out.println("transition" +transition); //getting -1 over here
              if ((transition == Geofence.GEOFENCE_TRANSITION_ENTER)
                || (transition == Geofence.GEOFENCE_TRANSITION_EXIT)) {

                         //send notification over here
             }   

    } 

AndroidManifest.xml container Receiver

    <receiver android:name="com.example.GeofenceReceiver" android:exported="false">
    <intent-filter >
        <action android:name="com.example.ACTION_RECEIVE_GEOFENCE"/>
    </intent-filter>
</receiver>

So basically I am able to see my GeoFence getting created but i don't get notification for the same.

does anyone have a solution for this?

Lang answered 2/11, 2013 at 18:30 Comment(9)
still looking for answer?Rhinitis
yes still looking for an answer! @AndroidGeek: can u help?Lang
yeah sure... so you are not getting the transition notification only??Rhinitis
yes i am not getting the notification...but first i need to get the transition correctly..can u try and let me know..thanksLang
are you able to add Geofences to your List?? are you getting some result in onAddGeofencesResult() method ???Rhinitis
Add this line of code in onResume() of your activity LocalBroadcastManager.getInstance(this).registerReceiver(mGeofenceBroadcastReceiver, mIntentFilter);Rhinitis
Did you manage to get sol of this? If Yes please let me knowAnechoic
yes i got solution...just use the sample Android code as it is..it will work fine..if you are facing any problems...post it as a question and send me linkLang
Related: Geofencing Notification App for AndroidEndotoxin
S
3

Just check it sample code. u r taking Geo-fencing but you are not mention location client and location connect so that google play service not connect to client and you are not able to receive notification take google requester file and check main acitvity where geofence add in list and also connect location client hope so its work for you

Silk answered 29/6, 2014 at 16:27 Comment(0)
I
1

So from the comments you are saying that you are able to add a geofence but you are not getting a notification. Firstly it looks as if you have used the android's geofence sample code which is their on their website and you have changed it so it uses a receiver instead of a service. For me i did the same and this might not seem like the right solution my answer is :

1.) Follow the same steps/code in the google'e geofence : http://developer.android.com/training/location/geofencing.html

2.) since you are changing the service to a receiver , in your createRequestPendingIntent() method are you returning the right broadcast intent ? I mean you have this line but is it reaching there ? is something getting returned there ?

return PendingIntent.getBroadcast( mActivity,0,intent, PendingIntent.FLAG_UPDATE_CURRENT);

3.)Do you have a LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, mIntentFilter); in your onResume() ?

I would follow the google's sample project again and just make sure you are changing the service to receiver part right and you should be fine.

Informed answered 11/11, 2013 at 21:31 Comment(0)
B
0

I had the same problem. I think that's because you are using the application context for your pending intent, try to use the activity instead.

Boling answered 5/11, 2013 at 7:18 Comment(12)
I replace my PendingIntent with this: return PendingIntent.getBroadcast( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)Lang
Basically, I can add the geofence. When I tried to drag a marker manually from outside in the geofence, I dont get the notificationLang
did you update the mock location to the location client when you draged the marker?Boling
I didnt get what do you mean by mock location to the location client...can u please elaborate the same...here is link to my current code: pastie.org/8456475Lang
also, where in your code have you registered the location request callbacks?Boling
I have registered it in the AndroidManifest.xml file as mentioned above..do I need to add another receiver for location request?Lang
Ok, there 2 main issues from what I understand, The first is that you didnt register the location request to callback, The second is that once you drag the marker you need to some how update that location to the LocatioClient, read about it in: developer.android.com/training/location/location-testing.htmlBoling
are you on gmail? can u add me [email protected] ..Lets chat over thereLang
please can u share your gmail id ...we can chat over gmailLang
Aright, ill send you an email just be sure to post it here afterwards so it may help other people.Boling
ok sure I will post it back over here..please help me solve thisLang
This really isn't an answer, and as such probably should have been a comment on the OP.Poindexter

© 2022 - 2024 — McMap. All rights reserved.