chenjishi / android_location_demo

A demo for how to use the new location api provided by android, include sample code for Fused location, Geofencing and Activity recognition.
17 stars 4 forks source link

Do geofence trigger also, when your app is not active? #2

Open lordgreg opened 9 years ago

lordgreg commented 9 years ago

Hi,

I'm developing an app which, with other possible features, also uses Geofencing. Problem with EVERYONE having using built-in geofence api is, it does NOT trigger when app is closed down (press home button OR back then leave a phone to sleep a while). Do not wake it up and just do the thing that triggers geofence location change.

By how geofences work, it SHOULD NOT trigger or will trigger sometimes, not always. Have you perhaps had this kind of problem? If so, did you managed to find out the reason behind it?

Here are few links:

My own stackoverflow post: http://stackoverflow.com/questions/25752224/geofences-not-triggering-pendingintents-and-broadcastreceiver

Possible solution which doesn't work for me http://stackoverflow.com/questions/19505614/android-geofence-eventually-stop-getting-transition-intents/19521823#19521823

http://stackoverflow.com/questions/21414160/how-to-increase-consistency-of-android-geofence-enter-exit-notifications

https://groups.google.com/forum/#!topic/android-developers/mlHd8ECMmWI

http://stackoverflow.com/questions/17571333/geofencing-sample-app-is-not-working-with-mock-location

If you're willing to find the solution, please contact me.

Regards,

Gregor

chenjishi commented 9 years ago

you should use IntentService to receive geofencing event(not the receiver), you can see how i implemented in class GeofenceIntentService in my "android_loaction_demo", we tested it by walk, drive and bicycle, definitely worked even your app is not active!

lordgreg commented 9 years ago

Hi,

as stated in links I've posted. Service does not ALWAYS work. That's why I've gave so many links people complaining about service not triggering and suggesting to try with Receiver. On how many devices did you tested this? I was getting mixed results on Xperia Z, LG G3, Nexus 4, etc

chenjishi commented 9 years ago

we tested for nexus s, nexus 4, htc one, samgsung s3/s4, all worked charming. what's the difference about my project with this demo is i registered GCM in my project.

lordgreg commented 9 years ago

@chenjishi Hi again. I've tried to run your code on my emulator and I can't seem to get it to work.

capture

As you see, I've set coordinates to exact location and in the code too. When moving gps outside and inside this location, nothing gets triggered.

Am I missing something?

vikram1234 commented 9 years ago

Does anyone able to get Geofence working if app is not open or not in background?

I tired so many ways to get it working but did not help, it never triggers Enter Exit events if app is not exits (Open or in Background)

lordgreg commented 9 years ago

@vikram1234 as to ms knowledge, stackoverflow help and the help of the author of this app/demo, I never got the desired results either. Either, this is a dead end or the android developers didn't give the proper explanation on how to get this working.

Tried on 4.4.2, 4.4.4 and 5.0 versions. Live Phone or VM (built-in VM or Genymotion).

So far, nothing works.

vikram1234 commented 9 years ago

@lordgreg - Thank you for your quick reply.

Actually i have good news here, i have android 5.0 (Nexus-4) and was able to get location updates even app is closed after this post.

I used this plugin and modified a bit to receive alert when app is closed (not open, not in background). https://github.com/radshag/PhoneGap-Geofencing

If you need i will share the same.

Thank you!!!!

lordgreg commented 9 years ago

@vikram1234 this is fantastic news!

Do you mind sharing your Android code with BackgroundService or whichever you used for geo-entering and goe-exiting?

Also, did the trigger appear when you closed the app down and imediately forced transition or was the phone in deep sleep?

vikram1234 commented 9 years ago

@lordgreg - if you reviewed the code of that plugin, it has class ProximityReceiver extends BroadcastReceiver

@Override public void onReceive(Context context, Intent intent) { String id = (String) intent.getExtras().get("id"); Log.d(TAG, "received proximity alert for region " + id); DGGeofencing.getInstance().fireRegionChangedEvent(intent); }

Here it receives updates, but if app is not around (open or background), it shows "Unfortunately app is closed", that is because DGGeofencing.getInstance() - it does not returns any singleton object, so it does not work, i changed it a bit as below, i am directly sending notification if instance does not exits or you can call any db or other operations.

if(DGGeofencing.getInstance() != null){ DGGeofencing.getInstance().fireRegionChangedEvent(intent); }
else {

        String status = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false) ? "entering" : "exiting";

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        int defaults = Notification.DEFAULT_ALL;
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                    .setDefaults(defaults)
                    .setSmallIcon(context.getApplicationInfo().icon)
                    .setWhen(System.currentTimeMillis())
                    .setContentTitle("Floral")
                    .setTicker("Floral")
                    .setContentIntent(contentIntent)
                    .setAutoCancel(true);

            String message = "Status of my event - "+status;
            if (message != null) {
                mBuilder.setContentText(message);
            } 

            String msgcnt = "1";
            if (msgcnt != null) {
                mBuilder.setNumber(Integer.parseInt(msgcnt));
            }

            int notId = 0;

            NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            String appName = "Test";

            mNotificationManager.notify((String) appName, notId, mBuilder.build());
    } 

How i tested -

1 - Installed app and wait until it registers geofence (lat, long).

2 - Closed the app (removed from background too)

3 - The distance i set was 10 meters and now started walking around.

I see alert in notification "Status of my event - entering" or "Status of my event - exit".

4 - Now i cleared all apps from background (No apps are open), i got alert too, either phone is an sleep or not.

I have not tested other tests yet as it used to already work if app is open or in background.

Thanks,

lordgreg commented 9 years ago

@vikram1234 this is, to be honest of on the biggest breakthroughs since my development of geofences in android. The sole reason I've also stopped with the development. NONE of android geofence developers never replied on official forums, g+ pages etc. No response whatsoever.

Before I myself start trying to implement this idea, there's one more question I'd like to ask you. Which Location setting have you tried it with?

Thank you so much for discussing this with me!

vikram1234 commented 9 years ago

@lordgreg - its #1

battery friendly (using only cellular networks and wifi) - Enter and exit events. Check it if works for you, if you need any help you can, reach me if needed.

vikram1234 commented 9 years ago

@lordgreg Just one update if you are looking to implement it - If you reboot your device, and want to get working geofence without opening app, you have to add following permissions.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<receiver android:name="Yourbroadcastreceiverclass" android:enabled="true" android:exported="false"> <intent-filter android:priority="1001"> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver>

zhangwei9046 commented 7 years ago

Hello, I just found this demo app very useful for my investigation into geofencing. But I don't know how to run this code, it seems not a gradle project, or part of the project? Would you please give me some instruction on how to setup the project? Or take me a screenshot of the project structure? Thank you!

lordgreg commented 7 years ago

@zhangwei9046 have you tried to import the folder in eclupse or android studio? should work.

zhangwei9046 commented 7 years ago

I use android studio. Should I put these two packages under app? Is it possible for you to take a screenshot of your project structure on the left side? That would be the most easy way, I think

nabilfx commented 7 years ago

Im using Unity, i need to implement Geofence, for IOs and android. Any help please?

gaurav-mishra8 commented 7 years ago

@lordgreg @vikram1234 any idea how apps like Life360 do this geofencing stuff ?

powder366 commented 7 years ago

Yes it works when you app is not active, but most often after a while it stops working. I reload my GeoFences on boot. Still is very unstable and it does not always work, or stop working. Don't know why? Surprised Google does not come out and say anything?!

nirav-prajapati-if commented 5 years ago

@nabilfx have you find another solution for that ? i am working on same thing if you have anything please guide me .Thanks

vikram1234 commented 5 years ago

@prakshif it’s been long time, I no longer use that product, sorry... just go through comments if that helps.

nirav-prajapati-if commented 5 years ago

@vikram1234 okay i want to use that in unity any idea about that?

matyasdanko commented 3 years ago

@powder366, @lordgreg, and others, I have an idea why geofencing in the background sometimes works and sometimes doesn't.

The reason is Android's inconsistent way of handling background services, workers, and tasks. Some manufacturers implemented their own system services to conserve battery life replacing Android's Battery Manager. Such services really don't like apps running in the background and background tasks/services and will eagerly shut them down when the parent activity/app leaves the foreground or when the user locks the screen. The most notorious manufacturers who do this are OnePlus and Huawei, but this issue can occur on ANY system that doesn't run an unmodified ("stock") Android, and even stock Android phones (like ones which are in the Android One program) are not fully exempt. I've tested this app and several others on a Xiaomi Mi A1 and it doesn't occur that often.

The way I got around this problem is

Keep in mind even doing all of these steps does not guarantee the app will keep running in the background indefinitely as Android can (and sometimes will) still destroy the app if and when it needs RAM and has no other way to free up RAM or when the user doesn't open the application (MainActivity or wherever you started your background service/task) for a long time. One example: when the user opens a lot of apps, Android may decide to kill your background service/process. If you design the background service/process to be lightweight you minimize the chance of this issue to occur but it will never be zero.

It has also caused issues with other Android libraries/apps.

Sources: https://issuetracker.google.com/issues/122098785 https://issuetracker.google.com/issues/123653024 https://www.davx5.com/faq/synchronization-is-not-run-as-expected https://bitbucket.org/copluk/acr/issues/607 https://slack.com/intl/en-hu/help/articles/360001562747-Known-issues-with-Android-notifications https://tasker.joaoapps.com/userguide/en/faqs/faq-problem.html#00