UNPKG

25.1 kBJavaScriptView Raw
1import { profile } from '../profiling';
2import { isEmbedded } from '../ui/embedding';
3import { SDK_VERSION } from '../utils/constants';
4import { ApplicationCommon } from './application-common';
5let BroadcastReceiver_;
6function initBroadcastReceiver() {
7 if (BroadcastReceiver_) {
8 return BroadcastReceiver_;
9 }
10 var BroadcastReceiverImpl = /** @class */ (function (_super) {
11 __extends(BroadcastReceiverImpl, _super);
12 function BroadcastReceiverImpl(onReceiveCallback) {
13 var _this = _super.call(this) || this;
14 _this._onReceiveCallback = onReceiveCallback;
15 return global.__native(_this);
16 }
17 BroadcastReceiverImpl.prototype.onReceive = function (context, intent) {
18 if (this._onReceiveCallback) {
19 this._onReceiveCallback(context, intent);
20 }
21 };
22 return BroadcastReceiverImpl;
23}(android.content.BroadcastReceiver));
24 BroadcastReceiver_ = BroadcastReceiverImpl;
25 return BroadcastReceiver_;
26}
27let NativeScriptLifecycleCallbacks_;
28function initNativeScriptLifecycleCallbacks() {
29 if (NativeScriptLifecycleCallbacks_) {
30 return NativeScriptLifecycleCallbacks_;
31 }
32 var NativeScriptLifecycleCallbacksImpl = /** @class */ (function (_super) {
33 __extends(NativeScriptLifecycleCallbacksImpl, _super);
34 function NativeScriptLifecycleCallbacksImpl() {
35 var _this = _super !== null && _super.apply(this, arguments) || this;
36 _this.activitiesCount = 0;
37 return _this;
38 }
39 NativeScriptLifecycleCallbacksImpl.prototype.onActivityCreated = function (activity, savedInstanceState) {
40 // console.log('NativeScriptLifecycleCallbacks onActivityCreated');
41 this.setThemeOnLaunch(activity);
42 if (!Application.android.startActivity) {
43 Application.android.setStartActivity(activity);
44 }
45 if (!this.nativescriptActivity && 'isNativeScriptActivity' in activity) {
46 this.nativescriptActivity = activity;
47 }
48 this.notifyActivityCreated(activity, savedInstanceState);
49 if (Application.hasListeners(Application.displayedEvent)) {
50 this.subscribeForGlobalLayout(activity);
51 }
52 };
53 NativeScriptLifecycleCallbacksImpl.prototype.onActivityDestroyed = function (activity) {
54 // console.log('NativeScriptLifecycleCallbacks onActivityDestroyed');
55 if (activity === Application.android.foregroundActivity) {
56 Application.android.setForegroundActivity(undefined);
57 }
58 if (activity === this.nativescriptActivity) {
59 this.nativescriptActivity = undefined;
60 }
61 if (activity === Application.android.startActivity) {
62 Application.android.setStartActivity(undefined);
63 // Fallback for start activity when it is destroyed but we have a known nativescript activity
64 if (this.nativescriptActivity) {
65 Application.android.setStartActivity(this.nativescriptActivity);
66 }
67 }
68 Application.android.notify({
69 eventName: Application.android.activityDestroyedEvent,
70 object: Application.android,
71 activity: activity,
72 });
73 // TODO: This is a temporary workaround to force the V8's Garbage Collector, which will force the related Java Object to be collected.
74 gc();
75 };
76 NativeScriptLifecycleCallbacksImpl.prototype.onActivityPaused = function (activity) {
77 // console.log('NativeScriptLifecycleCallbacks onActivityPaused');
78 if ('isNativeScriptActivity' in activity) {
79 Application.setSuspended(true, {
80 // todo: deprecate event.android in favor of event.activity
81 android: activity,
82 activity: activity,
83 });
84 }
85 Application.android.notify({
86 eventName: Application.android.activityPausedEvent,
87 object: Application.android,
88 activity: activity,
89 });
90 };
91 NativeScriptLifecycleCallbacksImpl.prototype.onActivityResumed = function (activity) {
92 // console.log('NativeScriptLifecycleCallbacks onActivityResumed');
93 Application.android.setForegroundActivity(activity);
94 // NOTE: setSuspended(false) is called in frame/index.android.ts inside onPostResume
95 // This is done to ensure proper timing for the event to be raised
96 Application.android.notify({
97 eventName: Application.android.activityResumedEvent,
98 object: Application.android,
99 activity: activity,
100 });
101 };
102 NativeScriptLifecycleCallbacksImpl.prototype.onActivitySaveInstanceState = function (activity, bundle) {
103 // console.log('NativeScriptLifecycleCallbacks onActivitySaveInstanceState');
104 Application.android.notify({
105 eventName: Application.android.saveActivityStateEvent,
106 object: Application.android,
107 activity: activity,
108 bundle: bundle,
109 });
110 };
111 NativeScriptLifecycleCallbacksImpl.prototype.onActivityStarted = function (activity) {
112 // console.log('NativeScriptLifecycleCallbacks onActivityStarted');
113 this.activitiesCount++;
114 if (this.activitiesCount === 1) {
115 Application.android.setInBackground(false, {
116 // todo: deprecate event.android in favor of event.activity
117 android: activity,
118 activity: activity,
119 });
120 }
121 Application.android.notify({
122 eventName: Application.android.activityStartedEvent,
123 object: Application.android,
124 activity: activity,
125 });
126 };
127 NativeScriptLifecycleCallbacksImpl.prototype.onActivityStopped = function (activity) {
128 // console.log('NativeScriptLifecycleCallbacks onActivityStopped');
129 this.activitiesCount--;
130 if (this.activitiesCount === 0) {
131 Application.android.setInBackground(true, {
132 // todo: deprecate event.android in favor of event.activity
133 android: activity,
134 activity: activity,
135 });
136 }
137 Application.android.notify({
138 eventName: Application.android.activityStoppedEvent,
139 object: Application.android,
140 activity: activity,
141 });
142 };
143 NativeScriptLifecycleCallbacksImpl.prototype.setThemeOnLaunch = function (activity) {
144 // Set app theme after launch screen was used during startup
145 var activityInfo = activity.getPackageManager().getActivityInfo(activity.getComponentName(), android.content.pm.PackageManager.GET_META_DATA);
146 if (activityInfo.metaData) {
147 var setThemeOnLaunch = activityInfo.metaData.getInt('SET_THEME_ON_LAUNCH', -1);
148 if (setThemeOnLaunch !== -1) {
149 activity.setTheme(setThemeOnLaunch);
150 }
151 }
152 };
153 NativeScriptLifecycleCallbacksImpl.prototype.notifyActivityCreated = function (activity, bundle) {
154 Application.android.notify({
155 eventName: Application.android.activityCreatedEvent,
156 object: Application.android,
157 activity: activity,
158 bundle: bundle,
159 });
160 };
161 NativeScriptLifecycleCallbacksImpl.prototype.subscribeForGlobalLayout = function (activity) {
162 var rootView = activity.getWindow().getDecorView().getRootView();
163 // store the listener not to trigger GC collection before collecting the method
164 global.onGlobalLayoutListener = new android.view.ViewTreeObserver.OnGlobalLayoutListener({
165 onGlobalLayout: function () {
166 Application.android.notify({
167 eventName: Application.displayedEvent,
168 object: Application,
169 android: Application.android,
170 activity: activity,
171 });
172 var viewTreeObserver = rootView.getViewTreeObserver();
173 viewTreeObserver.removeOnGlobalLayoutListener(global.onGlobalLayoutListener);
174 },
175 });
176 rootView.getViewTreeObserver().addOnGlobalLayoutListener(global.onGlobalLayoutListener);
177 };
178 var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11;
179 __decorate([
180 profile,
181 __metadata("design:type", Function),
182 __metadata("design:paramtypes", [typeof (_c = typeof androidx !== "undefined" && (_a = androidx.appcompat) !== void 0 && (_b = _a.app) !== void 0 && _b.AppCompatActivity) === "function" ? _c : Object, typeof (_e = typeof android !== "undefined" && (_d = android.os) !== void 0 && _d.Bundle) === "function" ? _e : Object]),
183 __metadata("design:returntype", void 0)
184 ], NativeScriptLifecycleCallbacksImpl.prototype, "onActivityCreated", null);
185 __decorate([
186 profile,
187 __metadata("design:type", Function),
188 __metadata("design:paramtypes", [typeof (_h = typeof androidx !== "undefined" && (_f = androidx.appcompat) !== void 0 && (_g = _f.app) !== void 0 && _g.AppCompatActivity) === "function" ? _h : Object]),
189 __metadata("design:returntype", void 0)
190 ], NativeScriptLifecycleCallbacksImpl.prototype, "onActivityDestroyed", null);
191 __decorate([
192 profile,
193 __metadata("design:type", Function),
194 __metadata("design:paramtypes", [typeof (_l = typeof androidx !== "undefined" && (_j = androidx.appcompat) !== void 0 && (_k = _j.app) !== void 0 && _k.AppCompatActivity) === "function" ? _l : Object]),
195 __metadata("design:returntype", void 0)
196 ], NativeScriptLifecycleCallbacksImpl.prototype, "onActivityPaused", null);
197 __decorate([
198 profile,
199 __metadata("design:type", Function),
200 __metadata("design:paramtypes", [typeof (_p = typeof androidx !== "undefined" && (_m = androidx.appcompat) !== void 0 && (_o = _m.app) !== void 0 && _o.AppCompatActivity) === "function" ? _p : Object]),
201 __metadata("design:returntype", void 0)
202 ], NativeScriptLifecycleCallbacksImpl.prototype, "onActivityResumed", null);
203 __decorate([
204 profile,
205 __metadata("design:type", Function),
206 __metadata("design:paramtypes", [typeof (_s = typeof androidx !== "undefined" && (_q = androidx.appcompat) !== void 0 && (_r = _q.app) !== void 0 && _r.AppCompatActivity) === "function" ? _s : Object, typeof (_u = typeof android !== "undefined" && (_t = android.os) !== void 0 && _t.Bundle) === "function" ? _u : Object]),
207 __metadata("design:returntype", void 0)
208 ], NativeScriptLifecycleCallbacksImpl.prototype, "onActivitySaveInstanceState", null);
209 __decorate([
210 profile,
211 __metadata("design:type", Function),
212 __metadata("design:paramtypes", [typeof (_x = typeof androidx !== "undefined" && (_v = androidx.appcompat) !== void 0 && (_w = _v.app) !== void 0 && _w.AppCompatActivity) === "function" ? _x : Object]),
213 __metadata("design:returntype", void 0)
214 ], NativeScriptLifecycleCallbacksImpl.prototype, "onActivityStarted", null);
215 __decorate([
216 profile,
217 __metadata("design:type", Function),
218 __metadata("design:paramtypes", [typeof (_0 = typeof androidx !== "undefined" && (_y = androidx.appcompat) !== void 0 && (_z = _y.app) !== void 0 && _z.AppCompatActivity) === "function" ? _0 : Object]),
219 __metadata("design:returntype", void 0)
220 ], NativeScriptLifecycleCallbacksImpl.prototype, "onActivityStopped", null);
221 __decorate([
222 profile,
223 __metadata("design:type", Function),
224 __metadata("design:paramtypes", [typeof (_3 = typeof androidx !== "undefined" && (_1 = androidx.appcompat) !== void 0 && (_2 = _1.app) !== void 0 && _2.AppCompatActivity) === "function" ? _3 : Object]),
225 __metadata("design:returntype", void 0)
226 ], NativeScriptLifecycleCallbacksImpl.prototype, "setThemeOnLaunch", null);
227 __decorate([
228 profile,
229 __metadata("design:type", Function),
230 __metadata("design:paramtypes", [typeof (_6 = typeof androidx !== "undefined" && (_4 = androidx.appcompat) !== void 0 && (_5 = _4.app) !== void 0 && _5.AppCompatActivity) === "function" ? _6 : Object, typeof (_8 = typeof android !== "undefined" && (_7 = android.os) !== void 0 && _7.Bundle) === "function" ? _8 : Object]),
231 __metadata("design:returntype", void 0)
232 ], NativeScriptLifecycleCallbacksImpl.prototype, "notifyActivityCreated", null);
233 __decorate([
234 profile,
235 __metadata("design:type", Function),
236 __metadata("design:paramtypes", [typeof (_11 = typeof androidx !== "undefined" && (_9 = androidx.appcompat) !== void 0 && (_10 = _9.app) !== void 0 && _10.AppCompatActivity) === "function" ? _11 : Object]),
237 __metadata("design:returntype", void 0)
238 ], NativeScriptLifecycleCallbacksImpl.prototype, "subscribeForGlobalLayout", null);
239 NativeScriptLifecycleCallbacksImpl = __decorate([
240 JavaProxy('org.nativescript.NativeScriptLifecycleCallbacks')
241 ], NativeScriptLifecycleCallbacksImpl);
242 return NativeScriptLifecycleCallbacksImpl;
243}(android.app.Application.ActivityLifecycleCallbacks));
244 NativeScriptLifecycleCallbacks_ = NativeScriptLifecycleCallbacksImpl;
245 return NativeScriptLifecycleCallbacks_;
246}
247let NativeScriptComponentCallbacks_;
248function initNativeScriptComponentCallbacks() {
249 if (NativeScriptComponentCallbacks_) {
250 return NativeScriptComponentCallbacks_;
251 }
252 var NativeScriptComponentCallbacksImpl = /** @class */ (function (_super) {
253 __extends(NativeScriptComponentCallbacksImpl, _super);
254 function NativeScriptComponentCallbacksImpl() {
255 return _super !== null && _super.apply(this, arguments) || this;
256 }
257 NativeScriptComponentCallbacksImpl.prototype.onLowMemory = function () {
258 gc();
259 java.lang.System.gc();
260 Application.notify({
261 eventName: Application.lowMemoryEvent,
262 object: Application,
263 android: this,
264 });
265 };
266 NativeScriptComponentCallbacksImpl.prototype.onTrimMemory = function (level) {
267 // TODO: This is skipped for now, test carefully for OutOfMemory exceptions
268 };
269 NativeScriptComponentCallbacksImpl.prototype.onConfigurationChanged = function (newConfiguration) {
270 Application.android.onConfigurationChanged(newConfiguration);
271 };
272 var _a, _b, _c;
273 __decorate([
274 profile,
275 __metadata("design:type", Function),
276 __metadata("design:paramtypes", []),
277 __metadata("design:returntype", void 0)
278 ], NativeScriptComponentCallbacksImpl.prototype, "onLowMemory", null);
279 __decorate([
280 profile,
281 __metadata("design:type", Function),
282 __metadata("design:paramtypes", [Number]),
283 __metadata("design:returntype", void 0)
284 ], NativeScriptComponentCallbacksImpl.prototype, "onTrimMemory", null);
285 __decorate([
286 profile,
287 __metadata("design:type", Function),
288 __metadata("design:paramtypes", [typeof (_c = typeof android !== "undefined" && (_a = android.content) !== void 0 && (_b = _a.res) !== void 0 && _b.Configuration) === "function" ? _c : Object]),
289 __metadata("design:returntype", void 0)
290 ], NativeScriptComponentCallbacksImpl.prototype, "onConfigurationChanged", null);
291 NativeScriptComponentCallbacksImpl = __decorate([
292 JavaProxy('org.nativescript.NativeScriptComponentCallbacks')
293 ], NativeScriptComponentCallbacksImpl);
294 return NativeScriptComponentCallbacksImpl;
295}(android.content.ComponentCallbacks2));
296 NativeScriptComponentCallbacks_ = NativeScriptComponentCallbacksImpl;
297 return NativeScriptComponentCallbacks_;
298}
299export class AndroidApplication extends ApplicationCommon {
300 constructor() {
301 super(...arguments);
302 this.activityCreatedEvent = AndroidApplication.activityCreatedEvent;
303 this.activityDestroyedEvent = AndroidApplication.activityDestroyedEvent;
304 this.activityStartedEvent = AndroidApplication.activityStartedEvent;
305 this.activityPausedEvent = AndroidApplication.activityPausedEvent;
306 this.activityResumedEvent = AndroidApplication.activityResumedEvent;
307 this.activityStoppedEvent = AndroidApplication.activityStoppedEvent;
308 this.saveActivityStateEvent = AndroidApplication.saveActivityStateEvent;
309 this.activityResultEvent = AndroidApplication.activityResultEvent;
310 this.activityBackPressedEvent = AndroidApplication.activityBackPressedEvent;
311 this.activityNewIntentEvent = AndroidApplication.activityNewIntentEvent;
312 this.activityRequestPermissionsEvent = AndroidApplication.activityRequestPermissionsEvent;
313 this._registeredReceivers = {};
314 this._pendingReceiverRegistrations = new Array();
315 }
316 init(nativeApp) {
317 if (this.nativeApp === nativeApp) {
318 return;
319 }
320 if (this.nativeApp) {
321 throw new Error('Application.android already initialized.');
322 }
323 this._nativeApp = nativeApp;
324 this._context = nativeApp.getApplicationContext();
325 this._packageName = nativeApp.getPackageName();
326 // we store those callbacks and add a function for clearing them later so that the objects will be eligable for GC
327 this.lifecycleCallbacks = new (initNativeScriptLifecycleCallbacks())();
328 this.nativeApp.registerActivityLifecycleCallbacks(this.lifecycleCallbacks);
329 this.componentCallbacks = new (initNativeScriptComponentCallbacks())();
330 this.nativeApp.registerComponentCallbacks(this.componentCallbacks);
331 this._registerPendingReceivers();
332 }
333 _registerPendingReceivers() {
334 this._pendingReceiverRegistrations.forEach((func) => func(this.context));
335 this._pendingReceiverRegistrations.length = 0;
336 }
337 onConfigurationChanged(configuration) {
338 this.setOrientation(this.getOrientationValue(configuration));
339 this.setSystemAppearance(this.getSystemAppearanceValue(configuration));
340 }
341 getNativeApplication() {
342 let nativeApp = this.nativeApp;
343 if (nativeApp) {
344 return nativeApp;
345 }
346 // Try getting it from module - check whether application.android.init has been explicitly called
347 // check whether the com.tns.NativeScriptApplication type exists
348 if (com.tns.NativeScriptApplication) {
349 nativeApp = com.tns.NativeScriptApplication.getInstance();
350 }
351 if (!nativeApp && isEmbedded()) {
352 nativeApp = com.tns.embedding.ApplicationHolder.getInstance();
353 }
354 // the getInstance might return null if com.tns.NativeScriptApplication exists but is not the starting app type
355 if (!nativeApp) {
356 // TODO: Should we handle the case when a custom application type is provided and the user has not explicitly initialized the application module?
357 const clazz = java.lang.Class.forName('android.app.ActivityThread');
358 if (clazz) {
359 const method = clazz.getMethod('currentApplication', null);
360 if (method) {
361 nativeApp = method.invoke(null, null);
362 }
363 }
364 }
365 // we cannot work without having the app instance
366 if (!nativeApp) {
367 throw new Error("Failed to retrieve native Android Application object. If you have a custom android.app.Application type implemented make sure that you've called the 'Application.android.init' method.");
368 }
369 return nativeApp;
370 }
371 get nativeApp() {
372 return this._nativeApp;
373 }
374 run(entry) {
375 if (this.started) {
376 throw new Error('Application is already started.');
377 }
378 this.started = true;
379 this.mainEntry = typeof entry === 'string' ? { moduleName: entry } : entry;
380 if (!this.nativeApp) {
381 const nativeApp = this.getNativeApplication();
382 this.init(nativeApp);
383 }
384 }
385 get startActivity() {
386 return this._startActivity;
387 }
388 get foregroundActivity() {
389 return this._foregroundActivity;
390 }
391 setStartActivity(value) {
392 this._startActivity = value;
393 }
394 setForegroundActivity(value) {
395 this._foregroundActivity = value;
396 }
397 get paused() {
398 return this.suspended;
399 }
400 get backgrounded() {
401 return this.inBackground;
402 }
403 get context() {
404 return this._context;
405 }
406 get packageName() {
407 return this._packageName;
408 }
409 // Possible flags are:
410 // RECEIVER_EXPORTED (2)
411 // RECEIVER_NOT_EXPORTED (4)
412 // RECEIVER_VISIBLE_TO_INSTANT_APPS (1)
413 registerBroadcastReceiver(intentFilter, onReceiveCallback, flags = 2) {
414 const registerFunc = (context) => {
415 const receiver = new (initBroadcastReceiver())(onReceiveCallback);
416 if (SDK_VERSION >= 26) {
417 context.registerReceiver(receiver, new android.content.IntentFilter(intentFilter), flags);
418 }
419 else {
420 context.registerReceiver(receiver, new android.content.IntentFilter(intentFilter));
421 }
422 this._registeredReceivers[intentFilter] = receiver;
423 };
424 if (this.context) {
425 registerFunc(this.context);
426 }
427 else {
428 this._pendingReceiverRegistrations.push(registerFunc);
429 }
430 }
431 unregisterBroadcastReceiver(intentFilter) {
432 const receiver = this._registeredReceivers[intentFilter];
433 if (receiver) {
434 this.context.unregisterReceiver(receiver);
435 this._registeredReceivers[intentFilter] = undefined;
436 delete this._registeredReceivers[intentFilter];
437 }
438 }
439 getRegisteredBroadcastReceiver(intentFilter) {
440 return this._registeredReceivers[intentFilter];
441 }
442 getRootView() {
443 const activity = this.foregroundActivity || this.startActivity;
444 if (!activity) {
445 return undefined;
446 }
447 const callbacks = activity['_callbacks'];
448 return callbacks ? callbacks.getRootView() : undefined;
449 }
450 resetRootView(entry) {
451 super.resetRootView(entry);
452 const activity = this.foregroundActivity || this.startActivity;
453 if (!activity) {
454 throw new Error('Cannot find android activity.');
455 }
456 // this.mainEntry = typeof entry === 'string' ? { moduleName: entry } : entry;
457 const callbacks = activity['_callbacks'];
458 if (!callbacks) {
459 throw new Error('Cannot find android activity callbacks.');
460 }
461 callbacks.resetActivityContent(activity);
462 }
463 getSystemAppearance() {
464 const resources = this.context.getResources();
465 const configuration = resources.getConfiguration();
466 return this.getSystemAppearanceValue(configuration);
467 }
468 // https://developer.android.com/guide/topics/ui/look-and-feel/darktheme#configuration_changes
469 getSystemAppearanceValue(configuration) {
470 const systemAppearance = configuration.uiMode & android.content.res.Configuration.UI_MODE_NIGHT_MASK;
471 switch (systemAppearance) {
472 case android.content.res.Configuration.UI_MODE_NIGHT_YES:
473 return 'dark';
474 case android.content.res.Configuration.UI_MODE_NIGHT_NO:
475 case android.content.res.Configuration.UI_MODE_NIGHT_UNDEFINED:
476 return 'light';
477 }
478 }
479 getOrientation() {
480 const resources = this.context.getResources();
481 const configuration = resources.getConfiguration();
482 return this.getOrientationValue(configuration);
483 }
484 getOrientationValue(configuration) {
485 const orientation = configuration.orientation;
486 switch (orientation) {
487 case android.content.res.Configuration.ORIENTATION_LANDSCAPE:
488 return 'landscape';
489 case android.content.res.Configuration.ORIENTATION_PORTRAIT:
490 return 'portrait';
491 default:
492 return 'unknown';
493 }
494 }
495 get android() {
496 // ensures Application.android is defined when running on Android
497 return this;
498 }
499}
500AndroidApplication.activityCreatedEvent = 'activityCreated';
501AndroidApplication.activityDestroyedEvent = 'activityDestroyed';
502AndroidApplication.activityStartedEvent = 'activityStarted';
503AndroidApplication.activityPausedEvent = 'activityPaused';
504AndroidApplication.activityResumedEvent = 'activityResumed';
505AndroidApplication.activityStoppedEvent = 'activityStopped';
506AndroidApplication.saveActivityStateEvent = 'saveActivityState';
507AndroidApplication.activityResultEvent = 'activityResult';
508AndroidApplication.activityBackPressedEvent = 'activityBackPressed';
509AndroidApplication.activityNewIntentEvent = 'activityNewIntent';
510AndroidApplication.activityRequestPermissionsEvent = 'activityRequestPermissions';
511export * from './application-common';
512export const Application = new AndroidApplication();
513export const iOSApplication = undefined;
514//# sourceMappingURL=application.android.js.map
\No newline at end of file