Example usage for java.lang Thread setDefaultUncaughtExceptionHandler

List of usage examples for java.lang Thread setDefaultUncaughtExceptionHandler

Introduction

In this page you can find the example usage for java.lang Thread setDefaultUncaughtExceptionHandler.

Prototype

public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) 

Source Link

Document

Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.

Usage

From source file:org.chromium.latency.walt.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Thread.setDefaultUncaughtExceptionHandler(new LoggingExceptionHandler());
    setContentView(R.layout.activity_main);

    // App bar// w ww  .jav a2  s .com
    toolbar = (Toolbar) findViewById(R.id.toolbar_main);
    setSupportActionBar(toolbar);
    getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            int stackTopIndex = getSupportFragmentManager().getBackStackEntryCount() - 1;
            if (stackTopIndex >= 0) {
                toolbar.setTitle(getSupportFragmentManager().getBackStackEntryAt(stackTopIndex).getName());
            } else {
                toolbar.setTitle(R.string.app_name);
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                // Disable fullscreen mode
                getSupportActionBar().show();
                getWindow().getDecorView().setSystemUiVisibility(0);
            }
        }
    });

    waltDevice = WaltDevice.getInstance(this);

    // Create front page fragment
    FrontPageFragment frontPageFragment = new FrontPageFragment();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.fragment_container, frontPageFragment);
    transaction.commit();

    logger = SimpleLogger.getInstance(this);
    broadcastManager = LocalBroadcastManager.getInstance(this);

    // Add basic version and device info to the log
    logger.log(String.format("WALT v%s  (versionCode=%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE));
    logger.log("WALT protocol version " + WaltDevice.PROTOCOL_VERSION);
    logger.log("DEVICE INFO:");
    logger.log("  " + Build.FINGERPRINT);
    logger.log("  Build.SDK_INT=" + Build.VERSION.SDK_INT);
    logger.log("  os.version=" + System.getProperty("os.version"));

    // Set volume buttons to control media volume
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    requestSystraceWritePermission();
    // Allow network operations on the main thread
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

From source file:org.apache.hadoop.yarn.server.applicationhistoryservice.ApplicationHistoryServer.java

static ApplicationHistoryServer launchAppHistoryServer(String[] args) {
    Thread.setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler());
    StringUtils.startupShutdownMessage(ApplicationHistoryServer.class, args, LOG);
    ApplicationHistoryServer appHistoryServer = null;
    try {//w  w w .ja v  a2 s .  com
        appHistoryServer = new ApplicationHistoryServer();
        ShutdownHookManager.get().addShutdownHook(new CompositeServiceShutdownHook(appHistoryServer),
                SHUTDOWN_HOOK_PRIORITY);
        YarnConfiguration conf = new YarnConfiguration();
        new GenericOptionsParser(conf, args);
        appHistoryServer.init(conf);
        appHistoryServer.start();
    } catch (Throwable t) {
        LOG.fatal("Error starting ApplicationHistoryServer", t);
        ExitUtil.terminate(-1, "Error starting ApplicationHistoryServer");
    }
    return appHistoryServer;
}

From source file:cat.ereza.customactivityoncrash.CustomActivityOnCrash.java

/**
 * Installs CustomActivityOnCrash on the application using the default error activity.
 *
 * @param context Context to use for obtaining the ApplicationContext. Must not be null.
 *//*  w  ww .j a  v a  2 s. c  om*/
public static void install(Context context) {
    try {
        if (context == null) {
            Log.e(TAG, "Install failed: context is null!");
        } else {
            if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                Log.w(TAG,
                        "CustomActivityOnCrash will be installed, but may not be reliable in API lower than 14");
            }

            //INSTALL!
            final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();

            if (oldHandler != null && oldHandler.getClass().getName().startsWith(CAOC_HANDLER_PACKAGE_NAME)) {
                Log.e(TAG, "You have already installed CustomActivityOnCrash, doing nothing!");
            } else {
                if (oldHandler != null
                        && !oldHandler.getClass().getName().startsWith(DEFAULT_HANDLER_PACKAGE_NAME)) {
                    Log.e(TAG,
                            "IMPORTANT WARNING! You already have an UncaughtExceptionHandler, are you sure this is correct? If you use ACRA, Crashlytics or similar libraries, you must initialize them AFTER CustomActivityOnCrash! Installing anyway, but your original handler will not be called.");
                }

                application = (Application) context.getApplicationContext();

                //We define a default exception handler that does what we want so it can be called from Crashlytics/ACRA
                Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                    @Override
                    public void uncaughtException(Thread thread, final Throwable throwable) {
                        Log.e(TAG,
                                "App has crashed, executing CustomActivityOnCrash's UncaughtExceptionHandler",
                                throwable);

                        if (hasCrashedInTheLastSeconds(application)) {
                            Log.e(TAG,
                                    "App already crashed in the last 2 seconds, not starting custom error activity because we could enter a restart loop. Are you sure that your app does not crash directly on init?",
                                    throwable);
                            if (oldHandler != null) {
                                oldHandler.uncaughtException(thread, throwable);
                                return;
                            }
                        } else {
                            setLastCrashTimestamp(application, new Date().getTime());

                            if (errorActivityClass == null) {
                                errorActivityClass = guessErrorActivityClass(application);
                            }

                            if (isStackTraceLikelyConflictive(throwable, errorActivityClass)) {
                                Log.e(TAG,
                                        "Your application class or your error activity have crashed, the custom activity will not be launched!");
                                if (oldHandler != null) {
                                    oldHandler.uncaughtException(thread, throwable);
                                    return;
                                }
                            } else if (launchErrorActivityWhenInBackground || !isInBackground) {

                                final Intent intent = new Intent(application, errorActivityClass);
                                StringWriter sw = new StringWriter();
                                PrintWriter pw = new PrintWriter(sw);
                                throwable.printStackTrace(pw);
                                String stackTraceString = sw.toString();

                                //Reduce data to 128KB so we don't get a TransactionTooLargeException when sending the intent.
                                //The limit is 1MB on Android but some devices seem to have it lower.
                                //See: http://developer.android.com/reference/android/os/TransactionTooLargeException.html
                                //And: http://stackoverflow.com/questions/11451393/what-to-do-on-transactiontoolargeexception#comment46697371_12809171
                                if (stackTraceString.length() > MAX_STACK_TRACE_SIZE) {
                                    String disclaimer = " [stack trace too large]";
                                    stackTraceString = stackTraceString.substring(0,
                                            MAX_STACK_TRACE_SIZE - disclaimer.length()) + disclaimer;
                                }

                                if (enableAppRestart && restartActivityClass == null) {
                                    //We can set the restartActivityClass because the app will terminate right now,
                                    //and when relaunched, will be null again by default.
                                    restartActivityClass = guessRestartActivityClass(application);
                                } else if (!enableAppRestart) {
                                    //In case someone sets the activity and then decides to not restart
                                    restartActivityClass = null;
                                }

                                String userLogString = "";
                                while (!userLogs.isEmpty()) {
                                    userLogString += userLogs.poll();
                                }

                                intent.putExtra(EXTRA_STACK_TRACE, stackTraceString);
                                intent.putExtra(EXTRA_USER_ACTION_TRACE, userLogString);
                                intent.putExtra(EXTRA_RESTART_ACTIVITY_CLASS, restartActivityClass);
                                intent.putExtra(EXTRA_SHOW_ERROR_DETAILS, showErrorDetails);
                                intent.putExtra(EXTRA_EVENT_LISTENER, eventListener);
                                intent.putExtra(EXTRA_IMAGE_DRAWABLE_ID, defaultErrorActivityDrawableId);
                                intent.setFlags(
                                        Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                if (eventListener != null) {
                                    eventListener.onLaunchErrorActivity();
                                }
                                application.startActivity(intent);
                            }
                        }
                        final Activity lastActivity = lastActivityCreated.get();
                        if (lastActivity != null) {
                            //We finish the activity, this solves a bug which causes infinite recursion.
                            //This is unsolvable in API<14, so beware!
                            //See: https://github.com/ACRA/acra/issues/42
                            lastActivity.finish();
                            lastActivityCreated.clear();
                        }
                        killCurrentProcess();
                    }
                });
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    application
                            .registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
                                int currentlyStartedActivities = 0;
                                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

                                @Override
                                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                                    if (activity.getClass() != errorActivityClass) {
                                        // Copied from ACRA:
                                        // Ignore activityClass because we want the last
                                        // application Activity that was started so that we can
                                        // explicitly kill it off.
                                        lastActivityCreated = new WeakReference<>(activity);
                                    }
                                    userLogs.add(dateFormat.format(new Date()) + " "
                                            + activity.getLocalClassName() + " created\n");
                                }

                                @Override
                                public void onActivityStarted(Activity activity) {
                                    currentlyStartedActivities++;
                                    isInBackground = (currentlyStartedActivities == 0);
                                    //Do nothing
                                }

                                @Override
                                public void onActivityResumed(Activity activity) {
                                    userLogs.add(dateFormat.format(new Date()) + " "
                                            + activity.getLocalClassName() + " resumed\n");
                                }

                                @Override
                                public void onActivityPaused(Activity activity) {
                                    userLogs.add(dateFormat.format(new Date()) + " "
                                            + activity.getLocalClassName() + " paused\n");
                                }

                                @Override
                                public void onActivityStopped(Activity activity) {
                                    //Do nothing
                                    currentlyStartedActivities--;
                                    isInBackground = (currentlyStartedActivities == 0);
                                }

                                @Override
                                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                                    //Do nothing
                                }

                                @Override
                                public void onActivityDestroyed(Activity activity) {
                                    userLogs.add(dateFormat.format(new Date()) + " "
                                            + activity.getLocalClassName() + " destroyed\n");
                                }
                            });
                }

                Log.i(TAG, "CustomActivityOnCrash has been installed.");
            }
        }
    } catch (Throwable t) {
        Log.e(TAG,
                "An unknown error occurred while installing CustomActivityOnCrash, it may not have been properly initialized. Please report this as a bug if needed.",
                t);
    }
}

From source file:org.akvo.flow.service.DataSyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    Thread.setDefaultUncaughtExceptionHandler(PersistentUncaughtExceptionHandler.getInstance());

    mProps = new PropertyUtil(getResources());
    mDatabase = new SurveyDbAdapter(this);
    mDatabase.open();/*from   w  ww  .  j av a2 s.  c  o m*/

    exportSurveys();// Create zip files, if necessary

    if (StatusUtil.hasDataConnection(this)) {
        syncFiles();// Sync everything
    }

    mDatabase.close();
}

From source file:com.planet57.gshell.MainSupport.java

public void boot(final String... args) throws Exception {
    checkNotNull(args);//from w w  w . j a  v a 2  s  . co m

    if (log.isDebugEnabled()) {
        log.debug("Booting w/args: {}", Arrays.toString(args));
    }

    // Register default handler for uncaught exceptions
    Thread.setDefaultUncaughtExceptionHandler(
            (thread, cause) -> log.warn("Unhandled exception occurred on thread: {}", thread, cause));

    // Prepare branding
    Branding branding = createBranding();

    // Process preferences
    PreferenceProcessor pp = new PreferenceProcessor();
    pp.setBasePath(branding.getPreferencesBasePath());
    pp.addBean(this);
    pp.process();

    // Process command line options & arguments
    CliProcessor clp = new CliProcessor();
    clp.addBean(this);
    clp.setStopAtNonOption(true);

    // cope with cli exceptions; which are expected
    try {
        clp.process(args);
    } catch (ParseException e) {
        e.printStackTrace(System.err);
        exit(2);
    }

    // once options are processed setup logging environment
    setupLogging(loggingLevel);

    // setup styling
    Styler.setSource(new MemoryStyleSource());

    // prepare terminal and I/O
    Terminal terminal = createTerminal(branding);
    IO io = StyledIO.create("shell", createStreamSet(terminal), terminal);

    if (help) {
        HelpPrinter printer = new HelpPrinter(clp, terminal.getWidth());
        printer.printUsage(io.out, branding.getProgramName());
        io.flush();
        exit(0);
    }

    if (version) {
        io.format("%s %s%n", branding.getDisplayName(), branding.getVersion());
        io.flush();
        exit(0);
    }

    // install thread-IO handler and attach streams
    threadIO.start();
    threadIO.setStreams(io.streams.in, io.streams.out, io.streams.err);

    Object result = null;
    try {
        variables.set(VariableNames.SHELL_ERRORS, showErrorTraces);

        Shell shell = createShell(io, variables, branding);
        shell.start();
        try {
            if (command != null) {
                result = shell.execute(command);
            } else if (appArgs != null) {
                result = shell.execute(String.join(" ", appArgs));
            } else {
                shell.run();
            }
        } finally {
            shell.stop();
        }
    } finally {
        io.flush();
        threadIO.stop();
        terminal.close();
    }

    if (result == null) {
        result = variables.get(VariableNames.LAST_RESULT);
    }

    exit(ExitCodeDecoder.decode(result));
}

From source file:io.anyline.cordova.AnylinePlugin.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    //should always be called, but unclear if the reset of the handler always works
    Thread.setDefaultUncaughtExceptionHandler(mDefaultUncaughtExceptionHandler);

    ResultReporter.setListener(null);//from  w  w w. j  ava  2 s  .  c  o  m
    if (resultCode == RESULT_OK) {
        //nothing todo, handeled with ResultReporter
    } else if (resultCode == RESULT_CANCELED) {
        mCallbackContext.error("Canceled");

    } else if (resultCode == RESULT_ERROR) {
        mCallbackContext.error(data.getStringExtra(EXTRA_ERROR_MESSAGE));
    }
}

From source file:com.twitter.heron.metricscachemgr.MetricsCacheManager.java

/**
 * Constructor: MetricsCacheManager needs 4 type information:
 * 1. Servers: host and 2 ports/*from   ww w  . ja  v  a2  s . c o m*/
 * 2. Topology: name
 * 3. Config: heron config, sink config, and cli config
 * 4. State: location node to be put in the state-mgr
 *
 * @param topologyName topology name
 * @param serverHost server host
 * @param masterPort port to accept message from sink
 * @param statsPort port to respond to query request
 * @param systemConfig heron config
 * @param metricsSinkConfig sink config
 * @param configExpand other config
 * @param metricsCacheLocation location for state mgr
 */
public MetricsCacheManager(String topologyName, String serverHost, int masterPort, int statsPort,
        SystemConfig systemConfig, MetricsSinksConfig metricsSinkConfig, Config configExpand,
        TopologyMaster.MetricsCacheLocation metricsCacheLocation) throws IOException {
    this.topologyName = topologyName;
    this.config = configExpand;
    this.metricsCacheLocation = metricsCacheLocation;

    metricsCacheManagerServerLoop = new NIOLooper();

    // initialize cache and hook to the shared nio-looper
    metricsCache = new MetricsCache(systemConfig, metricsSinkConfig, metricsCacheManagerServerLoop);

    // Init the HeronSocketOptions
    HeronSocketOptions serverSocketOptions = new HeronSocketOptions(
            systemConfig.getMetricsMgrNetworkWriteBatchSize(),
            systemConfig.getMetricsMgrNetworkWriteBatchTime(), systemConfig.getMetricsMgrNetworkReadBatchSize(),
            systemConfig.getMetricsMgrNetworkReadBatchTime(),
            systemConfig.getMetricsMgrNetworkOptionsSocketSendBufferSize(),
            systemConfig.getMetricsMgrNetworkOptionsSocketReceivedBufferSize(),
            systemConfig.getMetricsMgrNetworkOptionsMaximumPacketSize());

    // Construct the server to accepts messages from sinks
    metricsCacheManagerServer = new MetricsCacheManagerServer(metricsCacheManagerServerLoop, serverHost,
            masterPort, serverSocketOptions, metricsCache);

    metricsCacheManagerServer.registerOnMessage(TopologyMaster.PublishMetrics.newBuilder());
    metricsCacheManagerServer.registerOnRequest(TopologyMaster.MetricRequest.newBuilder());
    metricsCacheManagerServer.registerOnRequest(TopologyMaster.ExceptionLogRequest.newBuilder());

    // Construct the server to respond to query request
    metricsCacheManagerHttpServer = new MetricsCacheManagerHttpServer(metricsCache, statsPort);

    // Add exception handler for any uncaught exception here.
    Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
}

From source file:org.eobjects.datacleaner.bootstrap.Bootstrap.java

private void runInternal() throws FileSystemException {
    logger.info("Welcome to DataCleaner {}", Version.getVersion());

    // determine whether to run in command line interface mode
    final boolean cliMode = _options.isCommandLineMode();
    final CliArguments arguments = _options.getCommandLineArguments();

    logger.info("CLI mode={}, use -usage to view usage options", cliMode);

    if (cliMode) {

        if (!GraphicsEnvironment.isHeadless()) {
            // hide splash screen
            final SplashScreen splashScreen = SplashScreen.getSplashScreen();
            if (splashScreen != null) {
                splashScreen.close();/*w ww.j  a  v  a2 s  .com*/
            }
        }

        if (arguments.isUsageMode()) {
            final PrintWriter out = new PrintWriter(System.out);
            try {
                CliArguments.printUsage(out);
            } finally {
                FileHelper.safeClose(out);
            }

            exitCommandLine(null, 1);
            return;
        }
    }

    if (!cliMode) {
        // set up error handling that displays an error dialog
        final DCUncaughtExceptionHandler exceptionHandler = new DCUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);

        // init the look and feel
        LookAndFeelManager.get().init();
    }

    // initially use a temporary non-persistent user preferences object.
    // This is just to have basic settings available for eg. resolving
    // files.
    final UserPreferences initialUserPreferences = new UserPreferencesImpl(null);

    final String configurationFilePath = arguments.getConfigurationFile();
    final FileObject configurationFile = resolveFile(configurationFilePath, "conf.xml", initialUserPreferences);

    Injector injector = Guice.createInjector(new DCModule(DataCleanerHome.get(), configurationFile));

    // configuration loading can be multithreaded, so begin early
    final AnalyzerBeansConfiguration configuration = injector.getInstance(AnalyzerBeansConfiguration.class);

    // log usage
    final UsageLogger usageLogger = injector.getInstance(UsageLogger.class);
    usageLogger.logApplicationStartup();

    if (cliMode) {
        // run in CLI mode

        int exitCode = 0;
        final CliRunner runner = new CliRunner(arguments);
        try {
            runner.run(configuration);
        } catch (Throwable e) {
            logger.error("Error occurred while running DataCleaner command line mode", e);
            exitCode = 1;
        } finally {
            runner.close();
            exitCommandLine(configuration, exitCode);
        }
        return;
    } else {
        // run in GUI mode
        final AnalysisJobBuilderWindow analysisJobBuilderWindow;

        // initialize Mac OS specific settings
        final MacOSManager macOsManager = injector.getInstance(MacOSManager.class);
        macOsManager.init();

        // check for job file
        final String jobFilePath = _options.getCommandLineArguments().getJobFile();
        if (jobFilePath != null) {
            final FileObject jobFile = resolveFile(jobFilePath, null, initialUserPreferences);
            injector = OpenAnalysisJobActionListener.open(jobFile, configuration, injector);
        }

        final UserPreferences userPreferences = injector.getInstance(UserPreferences.class);

        analysisJobBuilderWindow = injector.getInstance(AnalysisJobBuilderWindow.class);

        final Datastore singleDatastore;
        if (_options.isSingleDatastoreMode()) {
            DatastoreCatalog datastoreCatalog = configuration.getDatastoreCatalog();
            singleDatastore = _options.getSingleDatastore(datastoreCatalog);
            if (singleDatastore == null) {
                logger.info("Single datastore mode was enabled, but datastore was null!");
            } else {
                logger.info("Initializing single datastore mode with {}", singleDatastore);
                analysisJobBuilderWindow.setDatastoreSelectionEnabled(false);
                analysisJobBuilderWindow.setDatastore(singleDatastore, true);
            }
        } else {
            singleDatastore = null;
        }

        // show the window
        analysisJobBuilderWindow.open();

        if (singleDatastore != null) {
            // this part has to be done after displaying the window (a lot
            // of initialization goes on there)
            final AnalysisJobBuilder analysisJobBuilder = analysisJobBuilderWindow.getAnalysisJobBuilder();
            final DatastoreConnection con = singleDatastore.openConnection();
            final InjectorBuilder injectorBuilder = injector.getInstance(InjectorBuilder.class);
            try {
                _options.initializeSingleDatastoreJob(analysisJobBuilder, con.getDataContext(),
                        injectorBuilder);
            } finally {
                con.close();
            }
        }

        final Image welcomeImage = _options.getWelcomeImage();
        if (welcomeImage != null) {
            // Ticket #834: make sure to show welcome dialog in swing's
            // dispatch thread.
            WidgetUtils.invokeSwingAction(new Runnable() {
                @Override
                public void run() {
                    final WelcomeDialog welcomeDialog = new WelcomeDialog(analysisJobBuilderWindow,
                            welcomeImage);
                    welcomeDialog.setVisible(true);
                }
            });
        }

        final WindowContext windowContext = injector.getInstance(WindowContext.class);

        final HttpClient httpClient = injector.getInstance(HttpClient.class);

        // set up HTTP service for ExtensionSwap installation
        loadExtensionSwapService(userPreferences, windowContext, configuration, httpClient, usageLogger);

        final ExitActionListener exitActionListener = _options.getExitActionListener();
        if (exitActionListener != null) {
            windowContext.addExitActionListener(exitActionListener);
        }
    }
}

From source file:com.bluewatcher.activity.BlueWatcherActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_blue_watcher);

    // ??????//ww w. j  a  v a2 s .  com
    String[] str = new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA,
            Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION, };
    for (String s : str) {
        if (checkSelfPermission(s) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, str, 1);
        }
    }

    PowerManager powerManager = getSystemService(PowerManager.class);
    if (!powerManager.isIgnoringBatteryOptimizations(getPackageName())) {
        Intent intent = new Intent(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    //????????????this?????
    //Context.getApplicationContext()???
    Context context = this.getApplicationContext();
    //??????????????
    //???????????????????
    //???????
    Thread.setDefaultUncaughtExceptionHandler(new CsUncaughtExceptionHandler(this, context));

    checkLicensing();
    checkBleSupported();

    NotificationAccessLauncher.requestAccess(this);
    ConfigurationManager.initialize(getPreferences(Context.MODE_PRIVATE));
    PhoneFinderConfigManager.resetFindMeFlag();

    boolean bluetoothEnabled = isBluetoothEnabled();
    if (bluetoothEnabled) {
        initializeBlueWatcher();
    }
}

From source file:dk.dma.ais.utils.filter.AisFilter.java

public static void main(String[] args) throws Exception {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override//w w w  .  ja  va 2s.c o  m
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println(
                    "Uncaught exception in thread " + t.getClass().getCanonicalName() + ": " + e.getMessage());
            System.exit(-1);
        }
    });
    final AisFilter aisFilter = new AisFilter();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            aisFilter.shutdown();
        }
    });
    aisFilter.execute(args);
}