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
5package org.chromium.content.app;
6
7import android.os.Looper;
8import android.os.MessageQueue;
9
10import org.chromium.base.BaseChromiumApplication;
11import org.chromium.base.library_loader.LibraryLoader;
12import org.chromium.content.browser.TracingControllerAndroid;
13
14/**
15 * Basic application functionality that should be shared among all browser applications
16 * based on the content layer.
17 */
18public class ContentApplication extends BaseChromiumApplication {
19    private TracingControllerAndroid mTracingController;
20
21    TracingControllerAndroid getTracingController() {
22        if (mTracingController == null) {
23            mTracingController = new TracingControllerAndroid(this);
24        }
25        return mTracingController;
26    }
27
28    @Override
29    public void onCreate() {
30        super.onCreate();
31
32        // Delay TracingControllerAndroid.registerReceiver() until the main loop is idle.
33        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
34            @Override
35            public boolean queueIdle() {
36                // Will retry if the native library has not been initialized.
37                if (!LibraryLoader.isInitialized()) return true;
38
39                try {
40                    getTracingController().registerReceiver(ContentApplication.this);
41                } catch (SecurityException e) {
42                    // Happens if the process is isolated. Ignore.
43                }
44                // Remove the idle handler.
45                return false;
46            }
47        });
48    }
49
50    /**
51     * For emulated process environment only. On a production device, the application process is
52     * simply killed without calling this method. We don't need to unregister the broadcast
53     * receiver in the latter case.
54     */
55    @Override
56    public void onTerminate() {
57        try {
58            getTracingController().unregisterReceiver(this);
59        } catch (SecurityException e) {
60            // Happens if the process is isolated. Ignore.
61        }
62
63        super.onTerminate();
64    }
65
66}
67