2015-09-14 14:35:58 +00:00
|
|
|
/**
|
|
|
|
* 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 BackAndroid
|
|
|
|
*/
|
|
|
|
|
|
|
|
'use strict';
|
|
|
|
|
|
|
|
var DeviceEventManager = require('NativeModules').DeviceEventManager;
|
|
|
|
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
|
|
|
|
|
|
|
|
var DEVICE_BACK_EVENT = 'hardwareBackPress';
|
|
|
|
|
|
|
|
type BackPressEventName = $Enum<{
|
|
|
|
backPress: string;
|
|
|
|
}>;
|
|
|
|
|
2016-03-23 19:21:07 +00:00
|
|
|
var _backPressSubscriptions = [];
|
2015-09-14 14:35:58 +00:00
|
|
|
|
|
|
|
RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() {
|
2016-03-23 19:21:07 +00:00
|
|
|
var propagate = true;
|
|
|
|
for (var i = _backPressSubscriptions.length - 1; i >= 0; i--) {
|
|
|
|
var subscription = _backPressSubscriptions[i];
|
2015-09-14 14:35:58 +00:00
|
|
|
if (subscription()) {
|
2016-03-23 19:21:07 +00:00
|
|
|
propagate = false;
|
|
|
|
break;
|
2015-09-14 14:35:58 +00:00
|
|
|
}
|
2016-03-23 19:21:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (propagate) {
|
2015-09-14 14:35:58 +00:00
|
|
|
BackAndroid.exitApp();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2015-09-17 14:20:44 +00:00
|
|
|
/**
|
2015-12-15 17:08:39 +00:00
|
|
|
* Detect hardware back button presses, and programmatically invoke the default back button
|
2015-09-17 14:20:44 +00:00
|
|
|
* functionality to exit the app if there are no listeners or if none of the listeners return true.
|
|
|
|
*
|
|
|
|
* Example:
|
|
|
|
*
|
|
|
|
* ```js
|
|
|
|
* BackAndroid.addEventListener('hardwareBackPress', function() {
|
|
|
|
* if (!this.onMainScreen()) {
|
|
|
|
* this.goBack();
|
|
|
|
* return true;
|
|
|
|
* }
|
|
|
|
* return false;
|
|
|
|
* });
|
|
|
|
* ```
|
|
|
|
*/
|
2015-09-14 14:35:58 +00:00
|
|
|
var BackAndroid = {
|
|
|
|
|
|
|
|
exitApp: function() {
|
|
|
|
DeviceEventManager.invokeDefaultBackPressHandler();
|
|
|
|
},
|
|
|
|
|
|
|
|
addEventListener: function (
|
|
|
|
eventName: BackPressEventName,
|
|
|
|
handler: Function
|
2016-03-23 19:21:07 +00:00
|
|
|
): void {
|
|
|
|
_backPressSubscriptions.push(handler);
|
2015-09-14 14:35:58 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
removeEventListener: function(
|
|
|
|
eventName: BackPressEventName,
|
|
|
|
handler: Function
|
|
|
|
): void {
|
2016-03-23 19:21:07 +00:00
|
|
|
var index = _backPressSubscriptions.indexOf(handler);
|
|
|
|
if (index !== -1) {
|
|
|
|
_backPressSubscriptions.splice(index, 1);
|
|
|
|
}
|
2015-09-14 14:35:58 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = BackAndroid;
|