Android app start and end event

android, detect when other apps are launched
android:windowdisablepreview
android detect when app is closed
android cold start
open app from background android
android run code when app is closed
app launch event in android
android black screen on app start

I have an app which track user activity on app which include time etc, Now if user has opened the app, It will start an session and till user in this app , his session will continue, He can switch to multiple activity. Now meantime he switches to another app, His session logging should be stopped and written down to file

What I tried

I created one base activity and On resume event if counter is zero, I start session and increment counter and On stop event , i decrement counter and if counter is zero, I stop session

But this will not calculate actual problem of tracking as android doesn't stop activity as user switch to another app.

So is there any way to achieve such thing.

Additional:

If we can get whether app activity is active on screen so event can be used to start or end session.

I can think of two ways of doing it:

Option 1:

You can create a service which scans for the current application on the foreground and see if it is your activity. Here is some code you can use, I took it from another answer:

There's an easy way of getting a list of running tasks from the ActivityManager service. You can request a maximum number of tasks running on the phone, and by default, the currently active task is returned first.

Once you have that you can get a ComponentName object by requesting the topActivity from your list.

Here's an example.

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);

     // get the info from the currently running task
     List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1); 

     Log.d("topActivity", "CURRENT Activity ::"
             + taskInfo.get(0).topActivity.getClassName());

     ComponentName componentInfo = taskInfo.get(0).topActivity;
   componentInfo.getPackageName();

You will need the following permission on your manifest:

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

Link to the answer: Android: How can I get the current foreground activity (from a service)?

You can call this every one second or less to detect if your app is still active. Please note that it is a deprecated and is not recommended for using for this kind of things, according to official documentation:

getRunningTasks()

Note: this method is only intended for debugging and presenting task management user interfaces. This should never be used for core logic in an application, such as deciding between different behaviors based on the information found here. Such uses are not supported, and will likely break in the future. For example, if multiple applications can be actively running at the same time, assumptions made about the meaning of the data here for purposes of control flow will be incorrect.


Option 2:

The second option is to create a class that extends Application with a flag, for example isAppRunning, which will be true or false according if your application is on the foreground or not:

public class MyAppContext extends Application {

   public boolean isAppRunning = true;

   public void setIsAppRunning(boolean v){
      isAppRunning = v;
   }

   public boolean isAppRunning(){
      return isAppRunning;
   }

}

Then on your AndroidManifest.xml you have to add this class so it will be used when your application starts. Just add android:name=".MyAppContext" under the application tag:

<application
        android:name=".MyAppContext"

Now in every activity that you have you should override onResume() and onPause() and set the flag to the corresponding value:

class BaseActivity extends Activity {


    @Override
    protected void onResume() {
        super.onResume();
        ((MyAppContext)getApplication()).setIsAppRunning(true);
    }

    @Override
    protected void onPause() {
        ((MyAppContext)getApplication()).setIsAppRunning(false);
        super.onPause();
    }
}

On this way every time you start an Activity the value of isAppRunning in MyAppContext will be true, when you exit the Activity it will be false but if another Activity opens (for example if you pressed the back button so you are returning to the previous activity) the value will be immediately true again.

When you finally finish all your Activities none of the onResume() methods will be called and all the onPause() methods will be called so isAppRunning will be false and you know your Activity is no longer on the foreground.

So resuming, if isAppRunning is true your application is on the foreground (start the session tracking) otherwise it's gone (stop the session tracking). You can create a Timer in MyAppContext class to check the value of isAppRunning periodically, so it would be:

public class MyAppContext extends Application {

   public boolean isAppRunning = true;
   public final int timerRate = 500;    // Execute timer task every 500mS

   public void setIsAppRunning(boolean v){
      isAppRunning = v;
   }

   public boolean isAppRunning(){
      return isAppRunning;
   }

   @Override
   public void onCreate() {
      super.onCreate();
      Timer mTimer = new Timer();

      mTimer.scheduleAtFixedRate(new TimerTask() {
         @Override
         public void run() {
            if(isAppRunning) startSesionTracking();
            else stopSesionTracking();
         }
      }, 0, REFRESH_TIME);
   }

   private void startSesionTracking () { ... };
   private void stopSesionTracking () { ... };

}

You should modify timerRate according to the precision you want to get in your session tracking.

How to detect Android application open and close: Background and , Especially if you are just starting out with Android development. So how do you detect when a user backgrounds and foregrounds your app. This is an example of how your could detect Application lifecycle events. Google just terminated our start-up Google Play Publisher Account on Christmas day. Some event interrupts app execution, as described in the onResume() section. This is the most common case. In Android 7.0 (API level 24) or higher, multiple apps run in multi-window mode. Because only one of the apps (windows) has focus at any time, the system pauses all of the other apps.

Extend all your Activities from BaseActivity like below. This is the best option for you as onPause and onResume methods are guaranteed to be called whenever your Activities show up or go away from phone screen.

class BaseActivity extends Activity {


    @Override
    protected void onResume() {
        super.onResume();
        // Start Logging
    }

    @Override
    protected void onPause() {
        super.onPause();
        // End Logging
    }
}

App startup time, Launch your game on Google Play · Create an Android App Bundle in Unity In the onCreate() method, you perform basic application startup logic that should up to the lifecycle of your activity it will receive the ON_CREATE event. call the super class onCreate to complete the creation of activity like Simple Calendar is a hugely customizable, offline calendar app free for Android mobile phones designed to do exactly what an android personal tiny calendar should do in 2020. No complicated features, unnecessary permissions and no ads! Whether you are looking for a simple mobile appointment reminder or you’re organizing single or recurring events, birthdays, need to remind anniversaries

1.Create a class named AppLifecycleTracker and paste this.

private class AppLifecycleTracker implements ActivityLifecycleCallbacks {
            private int numStarted = 0;
            private String TAG = "AppLifecycleTracker";


            private int numOfCreated = 0;

            @Override`enter code here`
            public void onActivityCreated(Activity activity, Bundle bundle) {
                if (numOfCreated == 0) {
                    Log.d(TAG, "onActivityCreated: app started");
                }
                numOfCreated++;
                Log.d(TAG, "onActivityCreated: " + numOfCreated);
            }

            @Override
            public void onActivityStarted(Activity activity) {
                if (numStarted == 0) {
                    // app went to foreground
                    Log.d(TAG, "onActivityStarted: foreground");

                }
                numStarted++;


            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                numStarted--;
                if (numStarted == 0) {
                    // app went to background
                    Log.d(TAG, "onActivityStarted: background");

                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                numOfCreated--;
                Log.d(TAG, "onActivityDestroyed: " + numOfCreated);
            }
        }

* in onActivityCreate if numOfCreated = 0, then you can say app has started. * in onActivityDestroyed if numOfCreated = 0, then you can say app is closed.

  1. Create a class extending Application, in onCreate, add this line

    registerActivityLifecycleCallbacks(new AppLifecycleTracker());

  2. set application name as the Application class in manifest.xml

Thats it. You are good to go.

Understand the Activity Lifecycle, Only in very critical (and undesireable) situations will the system get to a point where all cached processes are killed and it must start killing  How to force quit android application activity dynamically using button click event finish function. Closing android application activity programmatically is very easy using finish() method. Finish method closet all the all open existing activities and exit application user.

You need to look into Activity lifecycles on Android.

What you need is onPause - see the documentation here

I would also mention that onPause is fired even when switching between multiple activities, so you'd need to track when it's pausing to go to another screen.

Processes and Application Lifecycle, Apps running on Android 10 or higher can start activities only when one or or an activity in the back stack of the foreground task at the time finish() was called. All-day events use the start.date and end.date fields to specify when they occur. Note that the timezone field has no significance for all-day events. The start and end of the event must both be

You can easily do this by the source code below I mention which is also saved from orientation change . (Reference)

public class ApplicationEventTracker implements Application.ActivityLifecycleCallbacks {
private int activityReferences = 0;
private boolean isActivityChangingConfigurations = false;

@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}

@Override
public void onActivityStarted(Activity activity) {
    if (++activityReferences == 1 && !isActivityChangingConfigurations) {
        // App enters foreground
    }
}

@Override
public void onActivityResumed(Activity activity) {
}

@Override
public void onActivityPaused(Activity activity) {
}

@Override
public void onActivityStopped(Activity activity) {
    isActivityChangingConfigurations = activity.isChangingConfigurations();
    if (--activityReferences == 0 && !isActivityChangingConfigurations) {
        // App enters background
    }
}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}

@Override
public void onActivityDestroyed(Activity activity) {
}

Restrictions on starting activities from the background, android.app. Overview android.app.admin android.app.assist android.app. backup android.app.blob Event · UsageStats · UsageStatsManager. In most cases, every Android application runs in its own Linux process. This process is created for the application when some of its code needs to be run, and will remain running until it is no longer needed and the system needs to reclaim its memory …

android.app.Activity, start ID so we know which request we're stopping when we finish the system should continue the service in the event that the system kills it. Android will attempt to restart the app after it exits. You could end up in a loop. code to end its process: android.os.Process.killProcess(android.os.Process

Services overview, A guide to tracking app events in your Android app by using the Facebook SDK for Android. If you're adding the SDK to an existing project, start at step 3. class and set to true to re-enable event logging after the end-user provides consent. Android might decide that there are enough resources to keep the service in memory, so that it will be ready if it's needed again. – bigstones Apr 6 '11 at 12:01 | show 1 more comment 3 Answers 3

Android - App Events, Once you add App Center Analytics to your app and start the SDK, it will You can track your own custom events with up to 20 properties to  In order to make your OpenGL ES application respond to touch events, you must implement the onTouchEvent() method in your GLSurfaceView class. The example implementation below shows how to listen for MotionEvent.ACTION_MOVE events and translate them to an angle of rotation for a shape.

Comments
  • This is a deprecated API and doesn't always return the correct value. I am forced to use this in my app and it doesn't work all the time. The API docs clearly mentions that.
  • Yes, but I can't think of anything else to track an activity.
  • This is the simplest (and best) way to go at it, and also the recommended usage for most 3rd party APIs that require this (e.g. Flurry)
  • Looks like there may be a risk of double decrement if an activity is both stopped and destroyed.
  • so using onPause will not give app information about whether is it switching to another app or another activity...
  • No, this is just a part of the way Activities work, it runs when the activity is no longer in focus. This happens when the user switches to another app, another app takes foreground focus (I noticed this happens if you add a word to the dictionary on the keyboard) and even when the device is locked by the user, or the screen-timeout locks the device.
  • The way I did this was to use an application-level variable, and just set it to true when you're switching to another activity in your app - you know this because you're using startActivity(Intent intent). Reset it back to false in all the onResume methods in your activities.