|
| 1 | +/** |
| 2 | + * Copyright (c) 2015-present, Facebook, Inc. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the BSD-style license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. An additional grant |
| 7 | + * of patent rights can be found in the PATENTS file in the same directory. |
| 8 | + */ |
| 9 | + |
| 10 | +package com.facebook.react.modules.appstate; |
| 11 | + |
| 12 | +import com.facebook.react.bridge.Arguments; |
| 13 | +import com.facebook.react.bridge.Callback; |
| 14 | +import com.facebook.react.bridge.LifecycleEventListener; |
| 15 | +import com.facebook.react.bridge.ReactApplicationContext; |
| 16 | +import com.facebook.react.bridge.ReactContext; |
| 17 | +import com.facebook.react.bridge.ReactContextBaseJavaModule; |
| 18 | +import com.facebook.react.bridge.ReactMethod; |
| 19 | +import com.facebook.react.bridge.WritableMap; |
| 20 | + |
| 21 | +import static com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter; |
| 22 | + |
| 23 | +public class AppStateModule extends ReactContextBaseJavaModule |
| 24 | + implements LifecycleEventListener { |
| 25 | + |
| 26 | + private ReactContext mReactContext; |
| 27 | + private String mCurrentState = "background"; |
| 28 | + |
| 29 | + public AppStateModule(ReactApplicationContext context) { |
| 30 | + super(context); |
| 31 | + mReactContext = context; |
| 32 | + } |
| 33 | + |
| 34 | + @Override |
| 35 | + public String getName() { |
| 36 | + return "AppState"; |
| 37 | + } |
| 38 | + |
| 39 | + @Override |
| 40 | + public void initialize() { |
| 41 | + getReactApplicationContext().addLifecycleEventListener(this); |
| 42 | + } |
| 43 | + |
| 44 | + @ReactMethod |
| 45 | + public void getCurrentAppState(Callback success, Callback error) { |
| 46 | + success.invoke(createAppStateEventMap()); |
| 47 | + } |
| 48 | + |
| 49 | + @Override |
| 50 | + public void onHostResume() { |
| 51 | + mCurrentState = "active"; |
| 52 | + getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class) |
| 53 | + .emit("appStateDidChange", createAppStateEventMap()); |
| 54 | + } |
| 55 | + |
| 56 | + @Override |
| 57 | + public void onHostPause() { |
| 58 | + mCurrentState = "background"; |
| 59 | + getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class) |
| 60 | + .emit("appStateDidChange", createAppStateEventMap()); |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public void onHostDestroy() { |
| 65 | + |
| 66 | + } |
| 67 | + |
| 68 | + private WritableMap createAppStateEventMap() { |
| 69 | + WritableMap appState = Arguments.createMap(); |
| 70 | + appState.putString("app_state", mCurrentState); |
| 71 | + return appState; |
| 72 | + } |
| 73 | +} |
0 commit comments