any android application consists of many activities, only one activity can be in foreground.
so I want to know for a specific application how many times it takes while it is in the background.
I mean this
application starts -> application go to foreground -> user plays in the application -> application goes to bg (here I want to save the time) -> application goes to foreground (here I want to save the time)
by minusing the two times I could know what is the time which the application spends in the background, but that is a very hard work, because I have to edit the on pause and on resumes for all the activities, I have more than 200 activity.
hypothenticlly
I think the mainfest had something to deal with my problem but I couldn't find it.
One solution would be to create your own activity class (class that extends Activity) and use that as a base for all your activities. In your own activity you can keep code that all activities share.
You would still have to edit all you activities to extend this new class, but it is much easier to add things like this.
Write one super activity for all your 200 activities and extend super activity for every activity. Handle the time measurement in Superactivity of onpause() and onresume() methods.
Example :
Parent activity:
class ParentActivity extends Activity
{
// here in onResume and onPause methods handle your time measurment things...
}
ChildAcitivity:
class ChildActivity extends ParentActivity
{
#override
public void onPause()
{
super.onPause();
}
#override
public void onResume()
{
super.onResume();
}
}
Related
I'm working on my 1st Android app and wondering how to handle activation/deactivation/starting/stopping globally, not on Activity level.
This great article shows states transition for Activities:
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
Is there something similar for Application states?
For example at iOS and Windows Phone app there is clear app states separated from activities (views, controllers, whatever).
I'm asking because I want to perform certain operations only once per app loading/exiting not with every activity starting/stopping
The answer is There is Simply No Direct method to do this
rather than in Application Class you can catch these events
#Override
public void onLowMemory()
{
super.onLowMemory();
}
#Override
public void onTerminate()
{
super.onTerminate();
}
So you will have to handle it in all the Activities you will be having
the following methods
onResume()
onStart()
onRestart()
onPause()
onDestroy()
You will have to implement in all Activity to handle for all application
A suggesstion
You can have some Variable in Application class to save application state
say create a variable like
public static boolean isPaused;
and set it from all activity on state change
The question you're asking is applicable for iOS and Windows but not really for Android.
Android doesn't really have a concept of an application as an object, although there's an Application class. Instead, an app is a loose collection of Activities. There are many good reasons for this state of affairs; for example, it supports fast app switching and easy interaction between Activities of different apps.
The best way to coordinate your "app" so that one Activity doesn't try to do something that's already been done is to use SharedPreferences to store app state. Nearly every other way of doing it is less preferred. Even if the system kills off your entire app, SharedPreferences will maintain the current state. The Application object won't.
Also, Android is based on pausing and resuming. An Activity or activities are created, pause, and resume. They may be destroyed, but that's an extreme case. A corollary to this is that apps should not have an exit button; there's no need for one. I sometimes see apps that have one, but what they're really trying to do is shut down a background Service or process. The best way to do that is to have an affordance that says "Sleep" or similar.
Have all activities inherit from the same hierarchy and put whatever you want in OnCreate, OnPause, OnResume, OnStop, OnDestroy and call the super where applicable.
Example
Parent
IamTheParentActivity : Activity
protected void onCreate()
{
setApplicationState(ApplicationState.Running);
}
protected void onPause()
{
setApplicationState(ApplicationState.Paused);
}
private void setApplicationState(Enum ApplicationState)
{
//Some Application Level Variable
Application.State = ApplicationState
}
Children
IamTheChild : IamTheParentActivity
protected void override onCreate()
{
base.OnCreate;
do other stuff
}
I.e I would like to know when user interact with my application and when not.
I have tried do it using ActivityManager.getRecentTasks(). I have checked root activity at a top task to detect interact user with my application or not.
I have forced to check it in separated thread each second or two.
This way is bad for me. There is another way to detect when any activity of my app are opening or closed?
Have a look at the lifecycle of an Activity.
There are callback methods (onStart, onResume, onPause, onDestroy, ...) that are invoked by the system whenever your activity is created, becomes active or inactive etc.
You might create your own application class (just inherit from android.app.Application) and do your tracking there. The application will be around as long as your app is running.
For example you could put a flag or a counter there and set it from the activities' callbacks. A simple example for that could be:
public void onResume() {
super.onResume();
((MyApplication)getApplication()).active = true;
}
public void onDestroy() {
super.onDestroy();
((MyApplication)getApplication()).destroyed += 1;
}
Is there any way to get different event for application in background and particular activity in background?
In other words when any activity goes to background the onPause() method called, is there any to find that whole application goes to background?
Is there any settings for Manifest file to close the application when its goes to background.
Thanks,
AndroidIT
To identify if the application is in background:
There is a much more simpler approach:
On a BaseActivity that all Activities extend:
protected static boolean isVisible = false;
#Override
public void onResume()
{
super.onResume();
setVisible(true);
}
#Override
public void onPause()
{
super.onPause();
setVisible(false);
}
Whenever you need to check if any of your application activities is in foreground just check isVisible();
To understand this approach check this answer of side-by-side activity lifecycle: Activity side-by-side lifecycle
If you want to kill your application when it goes to background you have several options:
Something like this: Remove or close your own Activity window from a Status Bar Notification Intent modified for what you want.
Explore: android:finishOnTaskLaunch and android:excludeFromRecents and how you can make logic to make this effect (have done it already)
I would assume that all your activities are launched by one of the other activities in your app. If that is the case perhaps your activities could set flag indicating it is launching an activity. Then when onpause() is called this flag will determine if the app is being move to the background or simply launching the next activity.
save the state of each activity in shared preferences. each activity will need its own field in the preference file. each time you onResume or onPause, update the correct preference.
or: every time you onResume or onPause send a service a notification via intent that X activity has paused/resumed. the service will keep track of application state this way
I have an issue. For analytic purposes I need to track when the APP (not activity) is resumed. The problem I have now is that if I put the tracker on the OnResume event of an activity, it will get fired every time the user goes back and forth on different activities.
How can I avoid that? How can I track the real "Application Resume," (when user actually exits the app and come back) and not the activity resume?
Any ideas is greatly appreciated. Thanks.
I encountered the same problem and solved it by creating base activity :
public class mActivity extends Activity{
public static final String TAG = "mActivity";
public static int activities_num = 0;
#Override
protected void onStop() {
super.onStop();
activities_num--;
if(activities_num == 0){
Log.e(TAG,"user not longer in the application");
}
}
#Override
protected void onStart() {
super.onStart();
activities_num++;
}
}
all the other activities in my app inherited mActivity. When an activity is no longer visible than onStop is called. when activities_num == 0 than all activities are not visible (meaning the the user close the app or it passed to the background). When the user start the application (or restarting it from the background) onStart will be called (onStart is called when the activity is visible) and activities_num > 0. hopes it helps...
Use the Application object of your app (see http://developer.android.com/reference/android/app/Application.html). If you create a custom Application class and configure it in your AndroidManifest.xml file you can do something like this:
Start tracking in the onCreate() of the Application object.
Instrument all your Activities so their onPause() and onResume() methods check with the Application object and see if they are the first Activity to run, or if they are continuing a previously running instance of the app.
Stop tracking in the onDestroy() of the Application object.
To a certain degree most of the analytics packages (Flurry and their ilk) do something similar to this. You'll need to do a little state machine work to get this to work right, but it shouldn't be too complicated.
Instead of OnResume(), hook into the OnCreate() event of your main activity.
I have an application that has a user log in and log out. On a log in it tells my DataBase that the user is online. Problem I am having is that when the user doesnt use the app for a while and the processor kills my app is there a method or something where i can run my last piece of code to log them out? I looked at the android life cycle and i cannot use destroy because that only ties with that activity. Thanks!
I found a solution for this - not perfect but worked for me.
1.) Create a service to run in the background which is started when the first activity is created.
2.) Each activity binds to this service so it can "check-in" (i.e. it is alive and onPause) hasn't been called)
3.) In each activity register a broadcast receiver that listens for an intent fired by the service on a regular basis.
4.) On receiving the chech-in intent, it calls a service method which basically lets the service now there is an activity that is still alive (I tent to only respond to the intent if it had windowFocus
5.) If there is a check-in the service sleeps and then re-requests a checkin, if there was no check-in it sleeps for a shorter period of time, before re-requesting a check-in, if none respond then the app logs out. (The reason for the second re-quest when no check-ins were found was to account for issues surrounding check-in during an activity transition, i.e. starting a new activity and closing the current one).
As I said this isn't the nicest way to do it but seems to work for my needs so far.
why can't you use onDestroy method of your activity? if you have a lot of activities, you can create your own base activity class and derive all your activities from this base class.
public abstract class BaseActivity extends Activity {
....
#Override
public void onDestroy() {
super.onDestroy();
// do your stuff here
}
}
and thenm create all your activities like this:
public class YourActivity extends BaseActivity {
...
}
In AndroidManifest you've got name. Now create
public class MyName extends Application {
}
this is your Application class which is automatically created once user open your app. Now simply override onTerminate() method inside MyName class.
#Override
public void onTerminate() {
user.logOut();
super.onTerminate();
}
You can use your MyName class in every Activity simply with this code:
MyName myName= (MyName) this.getApplication();
myName.logUser(user);