Either show notification or react in application - java

I have a background service doing some work - retrieving user location by interval (launched with startService). As soon special condition reached I'd like to do the following:
If application is in foreground then start specific activity.
If application is not in foreground or closed then show the notification that will start required activity on tap.
I know how to show notification and how handle intent from server with broadcast receiver for example. But how can I determint if my application is in foreground? Or may be you can suggest complete better solution?

I determint if my application is in foreground
There's couple of ways to find out what is in front, but I actually prefer to track this myself (as this helps me apply additional logic if needed). Plus it's pretty simple task. To make this happen you need static int based counter somewhere (you can use your Application object if you have one, or have it elsewhere, does not really matter). In each Activity's onResume() you increment the counter by one, and in onPause() you decrement it by one. If counter equals 0 then none of your activities is in foreground so from your perspective you are in background and you post notification. For simplicity I always do that in my ActivityBase class all my activities extend.
If you do not want to track it yourself, you can use ActivityManager to see what's currently in foreground:
public boolean isAppInForeground() {
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = am.getRunningTasks(Integer.MAX_VALUE);
return (services.get(0).topActivity.getPackageName().toString()
.equalsIgnoreCase(getPackageName().toString()));
}
but this requires <uses-permission android:name="android.permission.GET_TASKS" /> entry in your Manifest, so not always welcome.

An alternative to Marcin's answers is to bind and unbind your Activities to the Service. This will allow communication between the Service and Activity whilst that binding exists, and the Service will know if an Activity that is capable of handling the scenario is currently available - e.g. you may not want to launch the Activity directly if the user is in the middle of some important process (like accepting the T&Cs / EULA or something), so the Service can tell the Activity that an event has happened, but the Activity can respond to the event correctly.

Related

service to check device state

I need to create an android service that:
Starts whenever the screen is on (whether it is at boot time or not)
sends a notification every 20 minutes (if the screen is on)
stops whenever the screen is off
Every tutorial I've read uses an activity, but I need this to be a service because the app is not supossed to be running other than when the user wants to change a setting. The documentation says I need an IntentService, but I cannot stop that manually and I cannot use a Service because it is a long running operation. I tried with an alarm manager but it didn't worked, I don't even bother to show you the code because I really don't understand it. I do not know how to make the service check if the screen is on or not, if I use a BroadcastReceiver it won't be inmediately processed so I am just stuck
To implement your requirement. You need 3 things such as Service, BroadcastReceiver & AlarmManager :
AlarmManager [which will fire after every 20 minutes]
Service [which will make changes like showing notification as system gets notifies after every 20 minutes for your particular msg]
BroadcastReceiver [which will check for screen on/off right from booting to shutting down]
Refer these links :
http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
http://androidexample.com/Screen_Wake_Sleep_Event_Listner_Service_-_Android_Example/index.php?view=article_discription&aid=91&aaid=115

Good practice of using android activities

I completed few android apps successfully but always I feel that I am not following the best practices of android developnment.
Few things which makes me feel developing a 100% complete android app is tough are
1. Making sure that my app is following all memory management stuffs
2.Making sure that my app is not going to crash
3.This one is always a big confusion for me-
I put all my code in oncreate() method including event listeners, phonestate listeners(If I require) etc..
What is the use of other methods like onResume(), onPause()... (I understood the concept of when they are called)
Should I stop all my event listeners in onPause() or by default android clears it?
Can I put all my event listener in onResume()?
Check dev Link
when ever over activity come in on stack again like previous it was not delete from stack then on resume is calling like if u want to see any list from any web service then after light off and again screen light is on then onresume() is call and u can call that webservices here and arrange list view with update values.
when ever your application go in pause mode then onpause() will call
you can follow above link i think your all query regards this will solve
The best reference for activity lifecycle callbacks is probably the the Android developers guide, and in particular this part:
http://developer.android.com/training/basics/activity-lifecycle/starting.html
Should I stop all my event listeners in onPause() or by default android clears it?
Either there or in onDestroy() but it depends what you're using them for; if you want the listener to listen even while that activity is paused or stopped then obv. stopping in onDestroy() is better.
Can I put all my event listener in onResume()?
It depends, onCreate() is only called once when your activity first starts up, whereas onResume() is called when your activity starts as well as every time your activity comes back from being paused or stopped. So if you stopped listening in onPause() then you probably want to start listening again in onResume(). If you stop listening in onDestroy() then you probably want to start listening in onCreate().

How to notify foreground activiy with event from background activity?

I have background activity in which I'm listening to Gps Location. Above it I have map activity.
How can I notify the map activity when an event occurred in the background after the activity already started?
I guess that this kind of question already been answered, but I tried googeling with many key words with no success, so sorry if it is duplicate. I'll appreciate references to other answer as well.
Thanks.
You probably shouldn't use an activity to perform a background task, it is extremely inefficient. I would recommend using a Service and communicate with Intents and a BroadcastReceiver. Services are designed to perform these kinds of operations.
You could also use an AsyncTask and communicate with the main thread with a Handler.
(All links are to the Android documentation for your reference)
You can use a broadcast to pass your data in an Intent (which is the main unit of communication between components in the Android platform). Check out the docs for BroadcastReceiver, it does a good job of spelling it out.
Also, worth noting, if your sender and activity are in the same process, you can use a LocalBroadcastManager to avoid IPC overhead.

How can I do some cleanup right before an Android app is quitting?

Is there some sort of onTerminate() method where I can do some cleanup (I want to clear some SharedPreferences) when my Android app is terminating?
I have an Activity that is keeping a running average of a few numbers, that I'm storing in a SharedPreference. I want this average to last while the app is running (the user can move between different activities) so I can't clear it on onDestroy() for that particular activity. I need to be able to clear it once the app is about to quit.
How can I do this?
I've not tried this, but here's what I would do:
As Alex mentioned in the comment to original question, use a Service to share the app-wide state between Activities.
Whenever you move between Activities, bind to the service from the "new" activity, and unbind from the "old" one. Check this to understand how to coordinate activities.
If you follow this properly, you can ensure that at least one Activity is always bound to the Service as long as your app is running; and that all Activities are unbound when the app is no longer running - at which point your service's onDestroy() is called. This is where you perform your cleanup.
So android doesn't really have a concept of an app being "finished". Unfortunently there is nothing synonymous to "onTerminate()". Is there some criteria by which you can decide when to clear your running average?
Use SharedPreference.Editor to remove the preferences, and commit. Here's a link for you: http://developer.android.com/reference/android/content/SharedPreferences.Editor.html

Android dialog management

I'm developing an android app (if you want more info http://www.txty.mobi) and I am having some problems with dialogs management. I'm quite new to Android so the way I'm doing things completely wrong. If the case please just say so pointing me to the right documentation to follow.
Background:
The main blocks of the app so far are one activity and one Service (which derives from IntentService).
The actvity needs to interact with the service in just two occasions: start/stop the service. The intent service will self regulate its lifetime using the AlarmManager.
A typical flow when clicking on start/stop:
1) the activity on its onResume registers a broadcast receiver to events sent by the service (unregisters it in the onPause)
2) the activity starts a indeterminate progress dialog
3) the activty sends a single shot alarm event (either start or stop) which will be send **straight away to the service
4) the service does what it needs to do to start
5) the service emits a broadcast event basically saying "done"
6) the activity receive this event and gets rid of the dialog.
The Problem:
The activity can lose its foreground status let's say if the user switches focus or a call is received, so the onPause method is called (at this point the activity could even be killed by the system to claim memory). obviously if this is the case the activity will never receive its broadcast event because the receiver has been unregistered. This will leave the app in the awkward situation, when the activity is brought again to the front, of having a dialog that you can't kill nor will never get rid of.
The (possible??) solution:
The way I am handling this now (apart for keeping the broadcast receiver in place) is by creating a utility class that uses preferences to keep track of which operations are being executed and their status:
Activity
- in the onResume using my utility class gets the list of operations the activity is waiting for
- check their status
- if they are completed perform some actions accordingly (in my case get rid of dialog!)
- delete the operation from the preferences.
- just before asking for a operation to the service it saves it to the preference using my utility class.
Service
perform operation and save state of the operation to the preference using my utility class.
emit broadcast.
Disasters happen!
Now this saves me in a normal situation, but if a disaster happens (i.e. with the task killer app you kill everything) the service might be killed before it can save the status of the operation I am stuck as before (the activity will think the operation is still going on so it won't touch the dialog). So as for now I add a Dismiss button to very dialog just in case :)
Now all of this looks too complicated for what I think should be a fairly common thing to do. That's why, as said at the beginning of the post, I might (very likely!) be completely wrong.
Any ideas? Apologies if this question has been asked already, I looked around but didn't find anything. Please point me to any resource online explaining this.
Thanks and sorry for the lenghty post :P
Luca
Have you tried using a StickyBroadcast? This caches the latest broadcast, so it can be received onResume. Please see this post.

Categories