1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_ANDROID_APPLICATION_STATUS_LISTENER_H_
6#define BASE_ANDROID_APPLICATION_STATUS_LISTENER_H_
7
8#include <jni.h>
9
10#include "base/android/jni_android.h"
11#include "base/base_export.h"
12#include "base/basictypes.h"
13#include "base/memory/ref_counted.h"
14#include "base/memory/singleton.h"
15#include "base/observer_list_threadsafe.h"
16
17namespace base {
18namespace android {
19
20// Define application state values like APPLICATION_STATE_VISIBLE in a
21// way that ensures they're always the same than their Java counterpart.
22enum ApplicationState {
23#define DEFINE_APPLICATION_STATE(x, y) APPLICATION_STATE_##x = y,
24#include "base/android/application_state_list.h"
25#undef DEFINE_APPLICATION_STATE
26};
27
28// A native helper class to listen to state changes of the Android
29// Application. This mirrors org.chromium.base.ApplicationStatus.
30// any thread.
31//
32// To start listening, create a new instance, passing a callback to a
33// function that takes an ApplicationState parameter. To stop listening,
34// simply delete the listener object. The implementation guarantees
35// that the callback will always be called on the thread that created
36// the listener.
37//
38// Example:
39//
40//    void OnApplicationStateChange(ApplicationState state) {
41//       ...
42//    }
43//
44//    // Start listening.
45//    ApplicationStatusListener* my_listener =
46//        new ApplicationStatusListener(
47//            base::Bind(&OnApplicationStateChange));
48//
49//    ...
50//
51//    // Stop listening.
52//    delete my_listener
53//
54class BASE_EXPORT ApplicationStatusListener {
55 public:
56  typedef base::Callback<void(ApplicationState)> ApplicationStateChangeCallback;
57
58  explicit ApplicationStatusListener(
59      const ApplicationStateChangeCallback& callback);
60  ~ApplicationStatusListener();
61
62  // Internal use: must be public to be called from base_jni_registrar.cc
63  static bool RegisterBindings(JNIEnv* env);
64
65  // Internal use only: must be public to be called from JNI and unit tests.
66  static void NotifyApplicationStateChange(ApplicationState state);
67
68 private:
69  void Notify(ApplicationState state);
70
71  ApplicationStateChangeCallback callback_;
72
73  DISALLOW_COPY_AND_ASSIGN(ApplicationStatusListener);
74};
75
76}  // namespace android
77}  // namespace base
78
79#endif  // BASE_ANDROID_APPLICATION_STATUS_LISTENER_H_
80