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:com.edduarte.argus.Main.java

private static void installUncaughtExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
        if (e instanceof ThreadDeath) {
            logger.warn("Ignoring uncaught ThreadDead exception.");
            return;
        }//from   www .  j  a v  a2s.c  om
        logger.error("Uncaught exception on cli thread, aborting.", e);
        System.exit(0);
    });
}

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

public void onCreate() {
    super.onCreate();
    Thread.setDefaultUncaughtExceptionHandler(PersistentUncaughtExceptionHandler.getInstance());
}

From source file:de.lespace.apprtc.CallActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Thread.setDefaultUncaughtExceptionHandler(new UnhandledExceptionHandler(this));

    // Set window styles for fullscreen-window size. Needs to be done before
    // adding content.
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().addFlags(//from  ww w  .j a  v a  2s. co m
            LayoutParams.FLAG_FULLSCREEN | LayoutParams.FLAG_KEEP_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD
                    | LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_TURN_SCREEN_ON);

    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

    setContentView(R.layout.activity_call);

    iceConnected = false;

    scalingType = ScalingType.SCALE_ASPECT_FILL;

    callFragment = new CallFragment();
    hudFragment = new HudFragment();

    // Create UI controls.
    localRender = (SurfaceViewRenderer) findViewById(R.id.local_video_view);
    remoteRender = (SurfaceViewRenderer) findViewById(R.id.remote_video_view);
    screenRender = (SurfaceViewRenderer) findViewById(R.id.remote_screen_view);

    localRenderLayout = (PercentFrameLayout) findViewById(R.id.local_video_layout);
    remoteRenderLayout = (PercentFrameLayout) findViewById(R.id.remote_video_layout);

    screenRenderLayout = (PercentFrameLayout) findViewById(R.id.remote_screen_layout);

    // Show/hide call control fragment on view click.
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            toggleCallControlFragmentVisibility();
        }
    };

    localRender.setOnClickListener(listener);
    remoteRender.setOnClickListener(listener);
    screenRender.setOnClickListener(listener); //screensharing

    // Create video renderers.
    rootEglBase = EglBase.create();
    localRender.init(rootEglBase.getEglBaseContext(), null);
    remoteRender.init(rootEglBase.getEglBaseContext(), null);
    screenRender.init(rootEglBase.getEglBaseContext(), null);
    localRender.setZOrderMediaOverlay(true);
    screenRender.setZOrderMediaOverlay(true);
    updateVideoView();

    setResult(RESULT_CANCELED);

    if (!broadcastIsRegistered) {
        registerReceiver(broadcast_reciever, new IntentFilter("finish_CallActivity"));
        registerReceiver(broadcast_reciever, new IntentFilter("finish_screensharing"));
        broadcastIsRegistered = true;
    }

    callFragment = new CallFragment();
    hudFragment = new HudFragment();
    // Send intent arguments to fragments.
    callFragment.setArguments(getIntent().getExtras());
    hudFragment.setArguments(getIntent().getExtras());

    // Activate call and HUD fragments and start the call.
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.add(R.id.call_fragment_container, callFragment);
    ft.add(R.id.hud_fragment_container, hudFragment);
    ft.commit();

    // For command line execution run connection for <runTimeMs> and exit.
    if (commandLineRun && runTimeMs > 0) {
        (new Handler()).postDelayed(new Runnable() {
            @Override
            public void run() {
                disconnect(false);
            }
        }, runTimeMs);
    }

    // Create and audio manager that will take care of audio routing,
    // audio modes, audio device enumeration etc.
    audioManager = AppRTCAudioManager.create(this, new Runnable() {
        // This method will be called each time the audio state (number and
        // type of devices) has been changed.
        @Override
        public void run() {
            onAudioManagerChangedState();
        }
    });

    // Store existing audio settings and change audio mode to
    // MODE_IN_COMMUNICATION for best possible VoIP performance.
    Log.d(TAG, "Initializing the audio manager...");
    audioManager.init();

    peerConnectionClient = PeerConnectionClient.getInstance(true);
    peerConnectionClient.createPeerConnectionFactory(CallActivity.this, peerConnectionParameters, this);

    peerConnectionClient.createPeerConnection(rootEglBase.getEglBaseContext(), localRender, remoteRender,
            screenRender, roomConnectionParameters.initiator);

    logAndToast("Creating OFFER...");
    // Create offer. Offer SDP will be sent to answering client in
    // PeerConnectionEvents.onLocalDescription event.
    peerConnectionClient.createOffer();
}

From source file:com.nullwire.trace.ExceptionHandler.java

/**
 * Register handler for unhandled exceptions.
 * @param app //from   ww w. j a  v  a  2 s . co  m
 * @param han
 */
public static boolean register(Context ctx, Handler han) {
    Log.i(TAG, "Registering default exceptions handler: " + G.URL);
    s_han = han;
    s_ctx = ctx;
    Log.i(TAG, "Registering default exceptions handler");
    // Get information about the Package
    PackageManager pm = s_ctx.getPackageManager();
    try {
        PackageInfo pi;
        // Version
        pi = pm.getPackageInfo(s_ctx.getPackageName(), 0);
        G.APP_VERSION = pi.versionName;
        // Package name
        G.APP_PACKAGE = pi.packageName;
        // Files dir for storing the stack traces
        G.FILES_PATH = s_ctx.getFilesDir().getAbsolutePath();
        // Device model
        G.PHONE_MODEL = android.os.Build.MODEL;
        // Android version
        G.ANDROID_VERSION = android.os.Build.VERSION.RELEASE;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    Log.i(TAG, "TRACE_VERSION: " + G.TraceVersion);
    Log.d(TAG, "APP_VERSION: " + G.APP_VERSION);
    Log.d(TAG, "APP_PACKAGE: " + G.APP_PACKAGE);
    Log.d(TAG, "FILES_PATH: " + G.FILES_PATH);
    Log.d(TAG, "URL: " + G.URL);

    boolean stackTracesFound = false;
    // We'll return true if any stack traces were found
    if (searchForStackTraces().length > 0) {
        stackTracesFound = true;
    }

    //it sends report
    new Thread() {
        @Override
        public void run() {
            s_han.post(new Runnable() {

                @Override
                public void run() {
                    String[] list = searchForStackTraces();
                    if (list != null && list.length > 0) {
                        AppHelper.showExceptionDialog(s_ctx);
                    }
                }
            });

            // First of all transmit any stack traces that may be lying around

            UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
            if (currentHandler != null) {
                Log.d(TAG, "current handler class=" + currentHandler.getClass().getName());
            }
            // don't register again if already registered
            if (!(currentHandler instanceof DefaultExceptionHandler)) {
                // Register default exceptions handler
                Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler(currentHandler));
            }
        }
    }.start();

    return stackTracesFound;
}

From source file:com.cosmicsubspace.nerdyaudio.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    final Thread.UncaughtExceptionHandler orig = Thread.getDefaultUncaughtExceptionHandler();
    final Context c = getApplicationContext();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override//from w  ww.j a v a  2s  .  c  o m
        public void uncaughtException(Thread thread, Throwable e) {
            Log2.log(0, this, "UncaughtException logged:", Log2.logToString(e));
            //Toast.makeText(c, ErrorLogger.logToString(e), Toast.LENGTH_SHORT).show();
            FileWriter f;
            try {
                f = new FileWriter(new File(Environment.getExternalStorageDirectory() + "/AFN_exceptions.txt"),
                        true);
                f.write("\n\n\n" + DateFormat.getDateTimeInstance().format(new Date()) + "\n");
                f.write(Log2.logToString(e));
                f.flush();
                f.close();
            } catch (IOException e1) {
                Log2.log(e1);
            } //Double exception?

            Log2.dumpLogsAsync();

            orig.uncaughtException(thread, e);
        }
    });

    requestPermission();

    Log2.log(1, this, "MainActivity Created!");

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    sf = getPreferences(Context.MODE_PRIVATE);

    String[] files = fileList();
    for (String i : files) {
        Log2.log(1, this, "File: " + i);
    }

    qm = QueueManager.getInstance();
    ap = AudioPlayer.getInstance();
    vb = VisualizationBuffer.getInstance();
    fm = FileManager.getInstance();
    wf = Waveform.getInstance();
    sbs = SidebarSettings.instantiate(getApplicationContext());
    vm = VisualizationManager.getInstance();

    volCtrl = new VolumeControls(getApplicationContext(), qm);

    //ap.setBufferFeedListener(vb);

    qm.passContext(getApplicationContext());
    fm.loadFromFile(this);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Library"));
    tabLayout.addTab(tabLayout.newTab().setText("Queue"));
    tabLayout.addTab(tabLayout.newTab().setText("Filters"));
    tabLayout.addTab(tabLayout.newTab().setText("Now Playing"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            int pos = tab.getPosition();
            if (pos == 0)
                ft.replace(R.id.tab_area, new LibraryFragment());
            else if (pos == 1)
                ft.replace(R.id.tab_area, new QueueFragment());
            else if (pos == 2)
                ft.replace(R.id.tab_area, new FiltersFragment());
            else if (pos == 3)
                ft.replace(R.id.tab_area, new NowPlayingFragment());

            ft.commit();
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
    getSupportFragmentManager().beginTransaction().replace(R.id.tab_area, new LibraryFragment()).commit();

    wfv = (PlayControlsView) findViewById(R.id.waveform);
    wfv.setSpacing(0);
    wfv.setTimestampVisibility(true);
    wfv.setTimestampSize(16);
    wfv.setTimestampColor(Color.WHITE);

    wfv.setTimestampOffset(30, 10);
    wfv.setTimestampBackgroundColor(Color.argb(128, 0, 0, 0));

    wfv.setWaveform(wf);
    qm.addQueueListener(wfv);
    qm.addProgressStringListener(wfv);

    vv = (VisualizationView) findViewById(R.id.visualization);

    dl = (DrawerLayout) findViewById(R.id.drawer_layout);

    dl.setDrawerListener(this);

    settingBtn = (RelativeLayout) findViewById(R.id.settings_btn);
    settingBtn.setOnClickListener(this);

    //statusText=(TextView)findViewById(R.id.status);

    sideContainer = (ScrollView) findViewById(R.id.drawer_scroll);
    sideContainer.addView(sbs.getView(getLayoutInflater(), sideContainer, null));

}

From source file:org.esupportail.nfctagdroid.NfcTacDroidActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ESUP_NFC_TAG_SERVER_URL = getEsupNfcTagServerUrl(getApplicationContext());
    //To keep session for desfire async requests
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    LocalStorage.getInstance(getApplicationContext());
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getApplicationContext()));
    setContentView(R.layout.activity_main);
    mAdapter = NfcAdapter.getDefaultAdapter(this);
    checkHardware(mAdapter);//from  ww  w .  ja v a2  s.  co m
    localStorageDBHelper = LocalStorage.getInstance(this.getApplicationContext());
    String numeroId = localStorageDBHelper.getValue("numeroId");
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String imei = telephonyManager.getDeviceId();
    url = ESUP_NFC_TAG_SERVER_URL + "/nfc-index?numeroId=" + numeroId + "&imei=" + imei + "&macAddress="
            + getMacAddr() + "&apkVersion=" + getApkVersion();
    view = (WebView) this.findViewById(R.id.webView);
    view.clearCache(true);
    view.addJavascriptInterface(new LocalStorageJavaScriptInterface(this.getApplicationContext()),
            "AndroidLocalStorage");
    view.addJavascriptInterface(new AndroidJavaScriptInterface(this.getApplicationContext()), "Android");

    view.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (progress == 100) {
                AUTH_TYPE = localStorageDBHelper.getValue("authType");
            }
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            log.info("Webview console message : " + consoleMessage.message());
            return false;
        }

    });

    view.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            view.reload();
            return true;
        }
    });
    view.getSettings().setAllowContentAccess(true);
    WebSettings webSettings = view.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDatabasePath(this.getFilesDir().getParentFile().getPath() + "/databases/");

    view.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }

    });

    view.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
        }
    });

    view.loadUrl(url);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

From source file:com.moto.miletus.application.tabs.ComponentsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View commandsLayout = inflater.inflate(R.layout.fragment_components, container, false);

    if (!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler)) {
        Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(this.getContext()));
    }/*from ww  w .  j  a v a 2s.  c o  m*/

    RecyclerView recyclerViewCommands = (RecyclerView) commandsLayout.findViewById(R.id.componentsList);
    progressBarLayout = (RelativeLayout) commandsLayout.findViewById(R.id.progressBarLayoutComponents);
    progressBar = (ProgressBar) commandsLayout.findViewById(R.id.progressBarComponents);

    // use this setting to improve performance if you know that changes
    // in content do not change the layout size of the RecyclerView
    recyclerViewCommands.setHasFixedSize(true);

    // use a linear layout manager
    recyclerViewCommands.setLayoutManager(new LinearLayoutManager(getActivity()));

    retrieveState(savedInstanceState != null ? savedInstanceState : getActivity().getIntent().getExtras());

    // specify an adapter (see also next example)
    componentsAdapter = new ComponentsAdapter(mDevice);
    recyclerViewCommands.setAdapter(componentsAdapter);
    recyclerViewCommands.setHasFixedSize(true);

    return commandsLayout;
}

From source file:io.teak.sdk.Raven.java

public void setAsUncaughtExceptionHandler() {
    if (Thread.getDefaultUncaughtExceptionHandler() instanceof Raven) {
        Raven raven = (Raven) Thread.getDefaultUncaughtExceptionHandler();
        raven.unsetAsUncaughtExceptionHandler();
    }/*from   w  w w  .ja  v a  2s.c o m*/
    previousUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(this);
}

From source file:VASSAL.launch.Launcher.java

protected Launcher(String[] args) {
    if (instance != null)
        throw new IllegalStateException();
    instance = this;

    LaunchRequest lreq = null;// ww  w . ja v a  2  s .c o m
    try {
        lreq = LaunchRequest.parseArgs(args);
    } catch (LaunchRequestException e) {
        System.err.println("VASSAL: " + e.getMessage());
        System.exit(1);
    }

    lr = lreq;

    // Note: We could do more sanity checking of the launch request
    // in standalone mode, but we don't bother because this is meant
    // only for debugging, not for normal use. If you pass nonsense
    // arguments (e.g., '-e' to the Player), don't expect it to work.
    final boolean standalone = lr.standalone;

    /*
        // parse the command line args now if we're standalone, since they
        // could be messed up and so we'll bail before setup
        LaunchRequest lr = null;
        if (standalone) {
          // Note: We could do more sanity checking of the launch request
          // in standalone mode, but we don't bother because this is meant
          // only for debugging, not for normal use. If you pass nonsense
          // arguments (e.g., '-e' to the Player), don't expect it to work.
          try {
            lr = LaunchRequest.parseArgs(args);
          }
          catch (LaunchRequestException e) {
            System.err.println("VASSAL: " + e.getMessage());
            System.exit(1);
          }
        }
    */

    // start the error log and setup system properties
    final StartUp start = SystemUtils.IS_OS_MAC_OSX ? new MacOSXStartUp() : new StartUp();

    start.startErrorLog();

    // log everything which comes across our stderr
    System.setErr(new PrintStream(new LoggedOutputStream(), true));

    logger.info(getClass().getSimpleName());
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
    start.initSystemProperties();

    // if we're not standalone, contact the module manager for instructions
    if (!standalone) {
        try {
            final int port = Integer.parseInt(System.getProperty("VASSAL.port"));

            final InetAddress lo = InetAddress.getByName(null);
            final Socket cs = new Socket(lo, port);

            ipc = new IPCMessenger(cs);

            ipc.addEventListener(CloseRequest.class, new CloseRequestListener());

            ipc.start();

            ipc.send(new StartedNotice(Info.getInstanceID()));
        } catch (IOException e) {
            // What we've got here is failure to communicate.
            ErrorDialog.show(e, "Error.communication_error",
                    Resources.getString(getClass().getSimpleName() + ".app_name"));
            System.exit(1);
        }
    }

    createMenuManager();

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                launch();
            } catch (ExtensionsLoader.LoadExtensionException e2) {
                warn(e2);
            } catch (IOException e1) {
                warn(e1);
            }
        }

        private void warn(Exception e1) {
            if (ipc == null) {
                // we are standalone, so warn the user directly
                ErrorDialog.showDetails(e1, ThrowableUtils.getStackTrace(e1), "Error.module_load_failed",
                        e1.getMessage());
            } else {
                // we have a manager, so pass the load failure back to it
                try {
                    ipc.send(new AbstractLaunchAction.NotifyOpenModuleFailed(lr, e1));
                } catch (IOException e2) {
                    // warn the user directly as a last resort
                    ErrorDialog.showDetails(e1, ThrowableUtils.getStackTrace(e1), "Error.module_load_failed",
                            e1.getMessage());

                    ErrorDialog.show(e2, "Error.communication_error",
                            Resources.getString(getClass().getSimpleName() + ".app_name"));
                }
            }

            System.exit(1);
        }
    });
}

From source file:org.apache.distributedlog.TestDistributedLogBase.java

@BeforeClass
public static void setupCluster() throws Exception {
    File zkTmpDir = IOUtils.createTempDir("zookeeper", "distrlog");
    tmpDirs.add(zkTmpDir);/*  w ww. ja  v  a2 s  .  co  m*/
    Pair<ZooKeeperServerShim, Integer> serverAndPort = LocalDLMEmulator.runZookeeperOnAnyPort(zkTmpDir);
    zks = serverAndPort.getLeft();
    zkPort = serverAndPort.getRight();
    bkutil = LocalDLMEmulator.newBuilder().numBookies(numBookies).zkHost("127.0.0.1").zkPort(zkPort)
            .serverConf(DLMTestUtil.loadTestBkConf()).shouldStartZK(false).build();
    bkutil.start();
    zkServers = "127.0.0.1:" + zkPort;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            LOG.warn("Uncaught exception at Thread {} : ", t.getName(), e);
        }
    });
}