1 // Copyright 2013 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_ACTIVITY_STATUS_H_ 6 #define BASE_ANDROID_ACTIVITY_STATUS_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 17 namespace base { 18 namespace android { 19 20 // Define activity state values like ACTIVITY_STATE_CREATED in a 21 // way that ensures they're always the same than their Java counterpart. 22 enum ActivityState { 23 #define DEFINE_ACTIVITY_STATE(x, y) ACTIVITY_STATE_##x = y, 24 #include "base/android/activity_state_list.h" 25 #undef DEFINE_ACTIVITY_STATE 26 }; 27 28 // A native helper class to listen to state changes of the current 29 // Android Activity. This mirrors org.chromium.base.ActivityStatus. 30 // any thread. 31 // 32 // To start listening, create a new instance, passing a callback to a 33 // function that takes an ActivityState 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 OnActivityStateChange(ActivityState state) { 41 // ... 42 // } 43 // 44 // // Start listening. 45 // ActivityStatus::Listener* my_listener = 46 // new ActivityStatus::Listener(base::Bind(&OnActivityStateChange)); 47 // 48 // ... 49 // 50 // // Stop listening. 51 // delete my_listener 52 // 53 class BASE_EXPORT ActivityStatus { 54 public: 55 typedef base::Callback<void(ActivityState)> StateChangeCallback; 56 57 class Listener { 58 public: 59 explicit Listener(const StateChangeCallback& callback); 60 ~Listener(); 61 62 private: 63 friend class ActivityStatus; 64 65 void Notify(ActivityState state); 66 67 StateChangeCallback callback_; 68 69 DISALLOW_COPY_AND_ASSIGN(Listener); 70 }; 71 72 // NOTE: The Java ActivityStatus is a singleton too. 73 static ActivityStatus* GetInstance(); 74 75 // Internal use: must be public to be called from base_jni_registrar.cc 76 static bool RegisterBindings(JNIEnv* env); 77 78 // Internal use only: must be public to be called from JNI and unit tests. 79 void OnActivityStateChange(ActivityState new_state); 80 81 private: 82 friend struct DefaultSingletonTraits<ActivityStatus>; 83 84 ActivityStatus(); 85 ~ActivityStatus(); 86 87 void RegisterListener(Listener* listener); 88 void UnregisterListener(Listener* listener); 89 90 scoped_refptr<ObserverListThreadSafe<Listener> > observers_; 91 92 DISALLOW_COPY_AND_ASSIGN(ActivityStatus); 93 }; 94 95 } // namespace android 96 } // namespace base 97 98 #endif // BASE_ANDROID_ACTIVITY_STATUS_H_ 99