1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_ANDROID_APPLICATION_STATUS_LISTENER_H_
6 #define BASE_ANDROID_APPLICATION_STATUS_LISTENER_H_
11 #include "base/android/jni_android.h"
12 #include "base/base_export.h"
13 #include "base/functional/callback_forward.h"
18 // Define application state values like APPLICATION_STATE_VISIBLE in a
19 // way that ensures they're always the same than their Java counterpart.
21 // Note that these states represent the most visible Activity state.
22 // If there are activities with states paused and stopped, only
23 // HAS_PAUSED_ACTIVITIES should be returned.
25 // A Java counterpart will be generated for this enum.
26 // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.base
27 enum ApplicationState {
28 APPLICATION_STATE_UNKNOWN = 0,
29 APPLICATION_STATE_HAS_RUNNING_ACTIVITIES = 1,
30 APPLICATION_STATE_HAS_PAUSED_ACTIVITIES = 2,
31 APPLICATION_STATE_HAS_STOPPED_ACTIVITIES = 3,
32 APPLICATION_STATE_HAS_DESTROYED_ACTIVITIES = 4
35 // A native helper class to listen to state changes of the Android
36 // Application. This mirrors org.chromium.base.ApplicationStatus.
39 // To start listening, create a new instance, passing a callback to a
40 // function that takes an ApplicationState parameter. To stop listening,
41 // simply delete the listener object. The implementation guarantees
42 // that the callback will always be called on the thread that created
47 // void OnApplicationStateChange(ApplicationState state) {
51 // // Start listening.
52 // auto my_listener = ApplicationStatusListener::New(
53 // base::BindRepeating(&OnApplicationStateChange));
58 // my_listener.reset();
60 class BASE_EXPORT ApplicationStatusListener {
62 using ApplicationStateChangeCallback =
63 base::RepeatingCallback<void(ApplicationState)>;
65 ApplicationStatusListener(const ApplicationStatusListener&) = delete;
66 ApplicationStatusListener& operator=(const ApplicationStatusListener&) =
69 virtual ~ApplicationStatusListener();
71 // Sets the callback to call when application state changes.
72 virtual void SetCallback(const ApplicationStateChangeCallback& callback) = 0;
74 // Notify observers that application state has changed.
75 virtual void Notify(ApplicationState state) = 0;
77 // Create a new listener. This object should only be used on a single thread.
78 static std::unique_ptr<ApplicationStatusListener> New(
79 const ApplicationStateChangeCallback& callback);
81 // Internal use only: must be public to be called from JNI and unit tests.
82 static void NotifyApplicationStateChange(ApplicationState state);
84 // Expose jni call for ApplicationStatus.getStateForApplication.
85 static ApplicationState GetState();
87 // Returns true if the app is currently foregrounded.
88 static bool HasVisibleActivities();
91 ApplicationStatusListener();
94 } // namespace android
97 #endif // BASE_ANDROID_APPLICATION_STATUS_LISTENER_H_