Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Android] AppState #5152

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions Examples/UIExplorer/AppStateExample.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @providesModule AppStateExample
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot for adding a cross-platform example!

* @flow
*/
'use strict';

var React = require('react-native');
var {
AppState,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

property AppState Property not found in Object.create

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can ignore this lint warning.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

property AppState Property not found in Object.create

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

property AppState Property not found in Object.create

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

property AppState Property not found in Object.create

Text,
View
} = React;

var AppStateSubscription = React.createClass({
getInitialState() {
return {
appState: AppState.currentState,
previousAppStates: [],
};
},
componentDidMount: function() {
AppState.addEventListener('change', this._handleAppStateChange);
},
componentWillUnmount: function() {
AppState.removeEventListener('change', this._handleAppStateChange);
},
_handleAppStateChange: function(appState) {
var previousAppStates = this.state.previousAppStates.slice();
previousAppStates.push(this.state.appState);
this.setState({
appState,
previousAppStates,
});
},
render() {
if (this.props.showCurrentOnly) {
return (
<View>
<Text>{this.state.appState}</Text>
</View>
);
}
return (
<View>
<Text>{JSON.stringify(this.state.previousAppStates)}</Text>
</View>
);
}
});

exports.title = 'AppState';
exports.description = 'app background status';
exports.examples = [
{
title: 'AppState.currentState',
description: 'Can be null on app initialization',
render() { return <Text>{AppState.currentState}</Text>; }
},
{
title: 'Subscribed AppState:',
description: 'This changes according to the current state, so you can only ever see it rendered as "active"',
render(): ReactElement { return <AppStateSubscription showCurrentOnly={true} />; }
},
{
title: 'Previous states:',
render(): ReactElement { return <AppStateSubscription showCurrentOnly={false} />; }
},
];
1 change: 1 addition & 0 deletions Examples/UIExplorer/UIExplorerList.android.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ var COMPONENTS = [
var APIS = [
require('./AccessibilityAndroidExample.android'),
require('./AlertExample').AlertExample,
require('./AppStateExample'),
require('./BorderExample'),
require('./ClipboardExample'),
require('./GeolocationExample'),
Expand Down
1 change: 1 addition & 0 deletions Examples/UIExplorer/UIExplorerList.ios.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ var APIS = [
require('./AnimatedExample'),
require('./AnimatedGratuitousApp/AnExApp'),
require('./AppStateIOSExample'),
require('./AppStateExample'),
require('./AsyncStorageExample'),
require('./BorderExample'),
require('./CameraRollExample.ios'),
Expand Down
147 changes: 147 additions & 0 deletions Libraries/AppState/AppState.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule AppState
* @flow
*/
'use strict';

var Map = require('Map');
var NativeModules = require('NativeModules');
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var RCTAppState = NativeModules.AppState;

var logError = require('logError');
var invariant = require('invariant');

var _eventHandlers = {
change: new Map(),
memoryWarning: new Map(),
};

/**
* `AppState` can tell you if the app is in the foreground or background,
* and notify you when the state changes.
*
* AppState is frequently used to determine the intent and proper behavior when
* handling push notifications.
*
* ### App States
*
* - `active` - The app is running in the foreground
* - `background` - The app is running in the background. The user is either
* in another app or on the home screen
* - `inactive` - This is a transition state that currently never happens for
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why document this if this never happens?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

according to blame @vjeux should know

* typical React Native apps.
*
* For more information, see
* [Apple's documentation](https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/TheAppLifeCycle/TheAppLifeCycle.html)
*
* ### Basic Usage
*
* To see the current state, you can check `AppState.currentState`, which
* will be kept up-to-date. However, `currentState` will be null at launch
* while `AppState` retrieves it over the bridge.
*
* ```
* getInitialState: function() {
* return {
* currentAppState: AppState.currentState,
* };
* },
* componentDidMount: function() {
* AppState.addEventListener('change', this._handleAppStateChange);
* },
* componentWillUnmount: function() {
* AppState.removeEventListener('change', this._handleAppStateChange);
* },
* _handleAppStateChange: function(currentAppState) {
* this.setState({ currentAppState, });
* },
* render: function() {
* return (
* <Text>Current state is: {this.state.currentAppState}</Text>
* );
* },
* ```
*
* This example will only ever appear to say "Current state is: active" because
* the app is only visible to the user when in the `active` state, and the null
* state will happen only momentarily.
*/

var AppState = {

/**
* Add a handler to AppState changes by listening to the `change` event type
* and providing the handler
*/
addEventListener: function(
type: string,
handler: Function
) {
invariant(
['change', 'memoryWarning'].indexOf(type) !== -1,
'Trying to subscribe to unknown event: "%s"', type
);
if (type === 'change') {
_eventHandlers[type].set(handler, RCTDeviceEventEmitter.addListener(
'appStateDidChange',
(appStateData) => {
handler(appStateData.app_state);
}
));
} else if (type === 'memoryWarning') {
_eventHandlers[type].set(handler, RCTDeviceEventEmitter.addListener(
'memoryWarning',
handler
));
}
},

/**
* Remove a handler by passing the `change` event type and the handler
*/
removeEventListener: function(
type: string,
handler: Function
) {
invariant(
['change', 'memoryWarning'].indexOf(type) !== -1,
'Trying to remove listener for unknown event: "%s"', type
);
if (!_eventHandlers[type].has(handler)) {
return;
}
_eventHandlers[type].get(handler).remove();
_eventHandlers[type].delete(handler);
},

// TODO: getCurrentAppState callback seems to be called at a really late stage
// after app launch. Trying to get currentState when mounting App component
// will likely to have the initial value here.
// Initialize to 'active' instead of null.
currentState: ('active' : ?string),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be a synchronous property? We can already see it not working properly.

If we really want it to be synchronous, another approach will be to set a constant initialState on native side which populates this value. Then subsequently change it on change events.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Could you please explain We can already see it not working properly what do you mean by it is not working?
  2. It seems that it works same way that you explained.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. As per your comment,
// TODO: getCurrentAppState callback seems to be called at a really late stage
// after app launch. Trying to get currentState when mounting App component
// will likely to have the initial value here.

The value is not really synchronous, and causes these kind of issues

  1. You're setting a property on JS and changing it, not defining a constant on Native, but whichever works


};

RCTDeviceEventEmitter.addListener(
'appStateDidChange',
(appStateData) => {
AppState.currentState = appStateData.app_state;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the naming convention? camelCase or underscores? @mkonicek @nicklockwood ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's camelCase in JS.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took it from ios https://github.com/facebook/react-native/blob/master/React/Modules/RCTAppState.m#L88. For now AppState and AppStateIOS are working with same obj-c implementation.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup let's keep it so we don't have to change the iOS implementation in this PR.

}
);

RCTAppState.getCurrentAppState(
(appStateData) => {
AppState.currentState = appStateData.app_state;
},
logError
);

module.exports = AppState;
1 change: 1 addition & 0 deletions Libraries/react-native/react-native.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ var ReactNative = {
get Animated() { return require('Animated'); },
get AppRegistry() { return require('AppRegistry'); },
get AppStateIOS() { return require('AppStateIOS'); },
get AppState() { return require('AppState'); },
get AsyncStorage() { return require('AsyncStorage'); },
get BackAndroid() { return require('BackAndroid'); },
get CameraRoll() { return require('CameraRoll'); },
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/

package com.facebook.react.modules.appstate;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter;

public class AppStateModule extends ReactContextBaseJavaModule
implements LifecycleEventListener {

public static final String APP_STATE_ACTIVE = "active";
public static final String APP_STATE_BACKGROUND = "background";

private String mAppState = "uninitialized";

public AppStateModule(ReactApplicationContext reactContext) {
super(reactContext);
}

@Override
public String getName() {
return "AppState";
}

@Override
public void initialize() {
getReactApplicationContext().addLifecycleEventListener(this);
}

@ReactMethod
public void getCurrentAppState(Callback success, Callback error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should return a Promise instead of callbacks.

@ReactMethod
public void getCurrentAppState(Promise promise) {
  promise.resolve(createAppStateEventMap();
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I use callback not to touch ios native code. It is internal api, in future we will be able to change it to promises.

success.invoke(createAppStateEventMap());
}

@Override
public void onHostResume() {
mAppState = APP_STATE_ACTIVE;
sendAppStateChangeEvent();
}

@Override
public void onHostPause() {
mAppState = APP_STATE_BACKGROUND;
sendAppStateChangeEvent();
}

@Override
public void onHostDestroy() {
// do not set state to destroyed, do not send an event. By the current implementation, the
// catalyst instance is going to be immediately dropped, and all JS calls with it.
}

private WritableMap createAppStateEventMap() {
WritableMap appState = Arguments.createMap();
appState.putString("app_state", mAppState);
return appState;
}

private void sendAppStateChangeEvent() {
getReactApplicationContext().getJSModule(RCTDeviceEventEmitter.class)
.emit("appStateDidChange", createAppStateEventMap());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.facebook.react.modules.network.NetworkingModule;
import com.facebook.react.modules.storage.AsyncStorageModule;
import com.facebook.react.modules.toast.ToastModule;
import com.facebook.react.modules.appstate.AppStateModule;
import com.facebook.react.modules.websocket.WebSocketModule;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.views.art.ARTRenderableViewManager;
Expand Down Expand Up @@ -56,6 +57,7 @@ public class MainReactPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(
new AppStateModule(reactContext),
new AsyncStorageModule(reactContext),
new ClipboardModule(reactContext),
new DialogModule(reactContext),
Expand All @@ -64,8 +66,8 @@ public List<NativeModule> createNativeModules(ReactApplicationContext reactConte
new LocationModule(reactContext),
new NetworkingModule(reactContext),
new NetInfoModule(reactContext),
new WebSocketModule(reactContext),
new ToastModule(reactContext));
new ToastModule(reactContext),
new WebSocketModule(reactContext));
}

@Override
Expand Down
1 change: 1 addition & 0 deletions website/server/extractDocs.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ var apis = [
'../Libraries/Animated/src/AnimatedImplementation.js',
'../Libraries/AppRegistry/AppRegistry.js',
'../Libraries/AppStateIOS/AppStateIOS.ios.js',
'../Libraries/AppState/AppState.js',
'../Libraries/Storage/AsyncStorage.js',
'../Libraries/Utilities/BackAndroid.android.js',
'../Libraries/CameraRoll/CameraRoll.js',
Expand Down