Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting state of application resume from different navigation state android

I want to record state of application when it is resumed/created from different point of entry.

  • app is opened from app drawer
  • app is opened from notification
  • app is opened from open apps (Long home press)
  • app is resumed from other screen

I know it can be traced by generating a base activity and overriding resume/pause events, but I have bulk of activity present in app. so is there any short method to get the state of application?


I thought about creating a service and continuously checking current running tasks, but I can only use this approach if I found a way to run the service only when my activity is in visible state. (for that to bind service in each activity is not practical for me)

like image 652
Hanry Avatar asked Nov 11 '22 12:11

Hanry


1 Answers

Your suggested solution sounds good to me:

public class YourBaseActivity extends Activity {

    @Override
    protected void onResume() {
        super.onResume();

        ActivityManager mgr = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = mgr.getRunningTasks(1);

        tasks.get(0).topActivity.getClassName();

        //Do what you need to do with it...
    }
}

And let all your activities extends this one instead of Activity should work for you


EDIT Another way to do it:

Create your own application class and implement Application.ActivityLifecycleCallbacks, a working example of the code:

public class ApplicationTest extends Application implements   Application.ActivityLifecycleCallbacks {
    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks(this);
    }

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

    @Override
    public void onActivityDestroyed(Activity activity) {
    }

    @Override
    public void onActivityPaused(Activity activity) {
    }

    @Override
    public void onActivityResumed(Activity activity) {
        Log.d("testing", "onActivityResumed");
    }

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

    @Override
    public void onActivityStarted(Activity activity) {
    }

    @Override
    public void onActivityStopped(Activity activity) {
    }
}

And reference this class in your manifest:

<application
    ...
    android:name="com.example.testing.ApplicationTest" >
like image 106
Guillermo Merino Avatar answered Nov 15 '22 13:11

Guillermo Merino