List of usage examples for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler
Thread.UncaughtExceptionHandler
From source file:com.matthewmitchell.peercoin_android_wallet.WalletApplication.java
private void initWallet() { new LinuxSecureRandom(); // init proper random number generator initLogging();//from w w w. java2 s .c o m Threading.throwOnLockCycles(); log.info("=== starting app using configuration: {}, {}", Constants.TEST ? "test" : "prod", Constants.NETWORK_PARAMETERS.getId()); super.onCreate(); CrashReporter.init(getCacheDir()); Threading.uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread thread, final Throwable throwable) { log.info("peercoinj uncaught exception", throwable); CrashReporter.saveBackgroundTrace(throwable, packageInfo); } }; initMnemonicCode(); config = new Configuration(PreferenceManager.getDefaultSharedPreferences(this)); walletFile = getFileStreamPath(Constants.Files.WALLET_FILENAME_PROTOBUF); // Rename old wallets final File oldWalletFile = getFileStreamPath(Constants.Files.WALLET_FILENAME_PROTOBUF_OLD); if (oldWalletFile.exists()) oldWalletFile.renameTo(walletFile); loadWalletFromProtobuf(); config.updateLastVersionCode(packageInfo.versionCode); afterLoadWallet(); cleanupFiles(); synchronized (this) { isLoaded = true; for (Runnable callback : loadedCallbacks) callback.run(); } }
From source file:org.hopestarter.wallet.WalletApplication.java
@Override public void onCreate() { new LinuxSecureRandom(); // init proper random number generator initLogging();/*from www . jav a 2 s. c o m*/ getDefaultTracker(); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().permitDiskReads() .permitDiskWrites().penaltyLog().build()); Threading.throwOnLockCycles(); log.info("=== starting app using configuration: {}, {}", Constants.TEST ? "test" : "prod", Constants.NETWORK_PARAMETERS.getId()); super.onCreate(); mPackageInfo = packageInfoFromContext(this); CrashReporter.init(getCacheDir()); Threading.uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread thread, final Throwable throwable) { log.info("bitcoinj uncaught exception", throwable); CrashReporter.saveBackgroundTrace(throwable, mPackageInfo); } }; initMnemonicCode(); initServerApi(); mConfig = new Configuration(PreferenceManager.getDefaultSharedPreferences(this), getResources()); mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); mBlockchainServiceIntent = new Intent(this, BlockchainServiceImpl.class); mBlockchainServiceCancelCoinsReceivedIntent = new Intent(BlockchainService.ACTION_CANCEL_COINS_RECEIVED, null, this, BlockchainServiceImpl.class); mBlockchainServiceResetBlockchainIntent = new Intent(BlockchainService.ACTION_RESET_BLOCKCHAIN, null, this, BlockchainServiceImpl.class); mWalletFile = getFileStreamPath(Constants.Files.WALLET_FILENAME_PROTOBUF); loadWalletFromProtobuf(); if (mConfig.versionCodeCrossed(mPackageInfo.versionCode, VERSION_CODE_SHOW_BACKUP_REMINDER) && !mWallet.getImportedKeys().isEmpty()) { log.info("showing backup reminder once, because of imported keys being present"); mConfig.armBackupReminder(); } mConfig.updateLastVersionCode(mPackageInfo.versionCode); mConfig.setExchangeCurrencyCode("EUR"); afterLoadWallet(); cleanupFiles(); }
From source file:biz.wiz.android.wallet.WalletApplication.java
@Override public void onCreate() { new LinuxSecureRandom(); // init proper random number generator initLogging();/*w ww . j a va 2 s. c om*/ StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().permitDiskReads() .permitDiskWrites().penaltyLog().build()); Threading.throwOnLockCycles(); log.info("=== starting app using configuration: {}, {}", Constants.TEST ? "test" : "prod", Constants.NETWORK_PARAMETERS.getId()); super.onCreate(); packageInfo = packageInfoFromContext(this); CrashReporter.init(getCacheDir()); Threading.uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread thread, final Throwable throwable) { log.info("bitcoinj uncaught exception", throwable); CrashReporter.saveBackgroundTrace(throwable, packageInfo); } }; initMnemonicCode(); config = new Configuration(PreferenceManager.getDefaultSharedPreferences(this)); activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); blockchainServiceIntent = new Intent(this, BlockchainServiceImpl.class); blockchainServiceCancelCoinsReceivedIntent = new Intent(BlockchainService.ACTION_CANCEL_COINS_RECEIVED, null, this, BlockchainServiceImpl.class); blockchainServiceResetBlockchainIntent = new Intent(BlockchainService.ACTION_RESET_BLOCKCHAIN, null, this, BlockchainServiceImpl.class); walletFile = getFileStreamPath(Constants.Files.WALLET_FILENAME_PROTOBUF); loadWalletFromProtobuf(); config.updateLastVersionCode(packageInfo.versionCode); afterLoadWallet(); }
From source file:com.linkedin.harisekhon.CLI.java
public final void main2(String[] args) { log.trace("running CLI.main2()"); setup();//from www . j a va 2s .co m try { addOptions(); } catch (IllegalArgumentException e) { usage(e); } try { parseArgs2(args); // autoflush(); // TODO: this will reduce TRACE level, check to only increase log level and never reduce it // if(verbose > 2) { // log.setLevel(Level.DEBUG); // } else if(verbose > 1){ // log.setLevel(Level.INFO); // } // if(debug){ // log.setLevel(Level.DEBUG); // } } catch (Exception e) { if (log.isDebugEnabled()) { e.printStackTrace(); } usage(e.getMessage()); } log.info(String.format("verbose level: %s", verbose)); validateInt(timeout, "timeout", 0, timeout_max); log.info(String.format("setting timeout to %s secs", timeout)); Thread t = new Thread(new Timeout(timeout)); t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { if (e instanceof QuitException) { println(((QuitException) e).status + ": " + ((QuitException) e).message); System.exit(getStatusCode("UNKNOWN")); } else { // normal Thread.stop() at end of program raises exception with null if (e.getMessage() != null) { println(e.getMessage()); System.exit(getStatusCode("UNKNOWN")); } } } }); t.start(); try { log.trace("running CLI.processArgs()"); processArgs(); log.trace("running CLI.run()"); run(); log.trace("running CLI.end()"); end(); log.trace("stopping timeout thread"); t.stop(); } catch (IllegalArgumentException e) { log.trace("caught exception in CLI.main2()"); if (log.isDebugEnabled()) { e.printStackTrace(); // not as nicely formatted - not printing anything right now?? // println(e.getStackTrace().toString()); } usage(e.getMessage()); // not thrown by try block, how is Control-C thrown? // } catch (InterruptedException e){ // System.out.println("Caught control-c..."); // System.exit(getStatusCode("UNKNOWN")); } }
From source file:au.edu.uq.cmm.paul.Paul.java
private void setupDefaultUncaughtExceptionHandler() { if (Thread.getDefaultUncaughtExceptionHandler() == null) { LOG.info("Setting the uncaught exception handler"); } else {//from www. j a v a2 s . c om LOG.info("Changing the uncaught exception handler"); } Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { LOG.error("Thread " + t.getName() + " died with an uncaught exception", e); } }); }
From source file:org.nebulaframework.grid.Grid.java
private static void initializeDefaultExceptionHandler() { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override/*from w w w. ja v a 2 s . co m*/ public void uncaughtException(Thread t, Throwable e) { log.fatal("[Uncaught Thread Exception] on Thread " + t.getName() + " - " + e, e); e.printStackTrace(); } }); }
From source file:org.mitre.svmp.activities.AppRTCActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_apprtc); getWindow().getDecorView().setBackgroundColor(Color.WHITE); ll = (LinearLayout) findViewById(R.id.vsvLinear); preparingTextView = (TextView) findViewById(R.id.preparingTextView); appLoadingImgVw = (ImageView) findViewById(R.id.appLoadingImgVw); // lock the application to the natural "up" orientation of the physical // device//from w w w . j a v a 2 s. c om // noinspection MagicConstant setRequestedOrientation(getDeviceDefaultOrientation()); // connect to the database dbHandler = new DatabaseHandler(this); // adapter that helps record performance measurements performanceAdapter = new PerformanceAdapter(); // Since the error-handling of this demo consists of throwing // RuntimeExceptions and we assume that'll terminate the app, we install // this default handler so it's applied to background threads as well. Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { e.printStackTrace(); System.exit(-1); } }); // Get info passed to Intent final Intent intent = getIntent(); connectionInfo = dbHandler.getConnectionInfo(intent.getIntExtra("connectionID", 1)); if (connectionInfo != null) connectToRoom(); else logAndToast(R.string.appRTC_toast_connection_notFound); }
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. *///from www .j ava 2 s. c o m 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:silvertrout.Network.java
private void createWorkerThread() { if (workerThread != null && !workerThread.isStop()) { throw new IllegalStateException("Can only start one instance of " + "workerthread for network \"" + getNetworkSettings().getName() + "\"!"); }//w w w .j av a 2 s. co m workerThread = new WorkerThread(); workerThread.setName("Network \"" + getNetworkSettings().getName() + "\" worker thread"); workerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { workerThread.cancel(); exceptionFrequenzy++; System.out.println( "*** Exception occured in network \"" + getNetworkSettings().getName() + "\": " + e); System.out.println("*** Exception frequenzy: " + exceptionFrequenzy); e.printStackTrace(); if (exceptionFrequenzy >= 3) { // number greater than 1. // Number found by injecting errors by messages. 3 seem // to be a good number. System.out.println("*** Too many exceptions! Closing " + " network \"" + getNetworkSettings().getName() + "\"!"); getConnection().forceClose(); return; } System.out.println("*** Creating new worker thread..."); createWorkerThread(); System.out.println( "*** New worker thread for network \"" + getNetworkSettings().getName() + "\" started!"); } }); System.err.println(" - Starting thread"); workerThread.start(); }
From source file:com.simadanesh.isatis.ScreenSlideActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CommonPlace.manehCodes = ManehCodeDA.getInstance(this).getAll(); CommonPlace.inspectionCodes = InspectionCodeDA.getInstance(this).getAll(); CommonPlace.CurrentRegisterFields = RegisterFieldDA.getInstance(this).getAll("fldPartitionCode=?", "", new String[] { CommonPlace.currentCityPartition.getFldPartitionCode() }); LoadValidationCriterias();// w w w. j ava 2 s .c o m Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread paramThread, Throwable paramThrowable) { Log.e("Alert", "Lets See if it Works !!!" + paramThrowable.toString()); } }); Utility.InitializeDefatultSettings(this); CommonPlace.slideActivity = this; getActionBar().setDisplayHomeAsUpEnabled(true); setContentView(R.layout.activity_screen_slide); mtextProgress = (TextView) findViewById(R.id.txtProgress); Utility.applyFont(findViewById(R.id.reading_page)); LinearLayout taskbarLayout = (LinearLayout) findViewById(R.id.taskbarpanel); taskbarLayout.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Button btnCamera = (Button) findViewById(R.id.btnCamera); if (btnCamera.getTextSize() > 0) { btnCamera.setTextSize(0); } else { btnCamera.setTextSize(20); } } }); progressbar = (ProgressBar) findViewById(R.id.reading_progress); progressbar.setProgress(0); Button btnSubmit = (Button) findViewById(R.id.btnSubmit); btnSubmit.setOnClickListener(new View.OnClickListener() { Dialog mydialog; public void onClick(View v) { ShowSubmitDialog(); } }); Button btnCamera = (Button) findViewById(R.id.btnCamera); btnCamera.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dispatchTakePictureIntentOrShowPicture(); } }); Button btnInspection = (Button) findViewById(R.id.btnInspection); btnInspection.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ShowInspectionDialog(); } }); Button btnonlineControl = (Button) findViewById(R.id.btnOnline_control); btnonlineControl.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ShowOnlineControl(); } }); Button btnOnlineCalculation = (Button) findViewById(R.id.btnCalculation); btnOnlineCalculation.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ShowOnlineCalculation(); } }); // Instantiate a ViewPager and a PagerAdapter. mPager = (ViewPager) findViewById(R.id.pager); mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager()); mPager.setAdapter(mPagerAdapter); mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { // When changing pages, reset the action bar actions since they are dependent // on which page is currently active. An alternative approach is to have each // fragment expose actions itself (rather than the activity exposing actions), // but for simplicity, the activity provides the actions in this sample. invalidateOptionsMenu(); } }); try { // int last = mSavedBundle.getInt("Reading-" + CommonPlace.currentReadingList.getId()); // mPager.setCurrentItem(last); } catch (Exception ex) { ex.toString(); } final Handler handler1 = new Handler(); try { final int pos = Integer.parseInt(CommonPlace.currentReadingList.Position); handler1.postDelayed(new Runnable() { @Override public void run() { mPager.setCurrentItem(pos); } }, 500); } catch (Exception ex) { } }