Example usage for java.lang Thread getDefaultUncaughtExceptionHandler

List of usage examples for java.lang Thread getDefaultUncaughtExceptionHandler

Introduction

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

Prototype

public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() 

Source Link

Document

Returns the default handler invoked when a thread abruptly terminates due to an uncaught exception.

Usage

From source file:myblog.richard.vewe.launcher3.LauncherApplication.java

public LauncherApplication() {
    defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    // setup handler for uncaught exception
    //TODO we should uncomment this
    //Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}

From source file:com.tcl.lzhang1.mymusic.AppException.java

/**
 * Instantiates a new app exception.
 */
private AppException() {
    this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
}

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  .jav  a 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:com.moto.miletus.application.tabs.CommandsFragment.java

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

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

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

    RecyclerView recyclerViewCommands = (RecyclerView) commandsLayout.findViewById(R.id.commandsList);

    // 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()));

    // specify an adapter (see also next example)
    commandsAdapter = new CommandsAdapter(this);
    recyclerViewCommands.setAdapter(commandsAdapter);
    recyclerViewCommands.setHasFixedSize(true);

    return commandsLayout;
}

From source file:at.maui.cheapcast.service.CheapCastService.java

@Override
public void onCreate() {
    super.onCreate();
    Log.d(LOG_TAG, "onCreate()");

    mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    mNetIf = Utils.getWifiNetworkInterface(mWifiManager);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mPreferences = getSharedPreferences("cheapcast", MODE_PRIVATE | MODE_MULTI_PROCESS);
    } else {//from  w w w.  j  a  v  a 2  s .  c om
        mPreferences = getSharedPreferences("cheapcast", MODE_PRIVATE);
    }
    Log.d(LOG_TAG, String.format("Starting up: friendlyName: %s",
            mPreferences.getString("friendly_name", "CheapCasto")));
    mGson = new Gson();

    mGoogleAnalytics = GoogleAnalytics.getInstance(this);
    mGaTracker = mGoogleAnalytics.getTracker(getString(R.string.ga_trackingId));
    mGoogleAnalytics.setAppOptOut(mPreferences.getBoolean("analytics", false));

    Thread.UncaughtExceptionHandler myHandler = new ExceptionReporter(mGaTracker, // Currently used Tracker.
            GAServiceManager.getInstance(), // GAServiceManager singleton.
            Thread.getDefaultUncaughtExceptionHandler(), this); // Current default uncaught exception handler.

    mGaTracker.sendEvent("CheapCastService", "ServiceStart", null, null);

    mRegisteredApps = new HashMap<String, App>();
    registerApp(new App("ChromeCast", "https://www.gstatic.com/cv/receiver.html?$query"));
    registerApp(new App("YouTube", "https://www.youtube.com/tv?$query"));
    registerApp(new App("PlayMovies", "https://play.google.com/video/avi/eureka?$query",
            new String[] { "play-movies", "ramp" }));
    registerApp(new App("GoogleMusic", "https://play.google.com/music/cast/player"));

    registerApp(new App("GoogleCastSampleApp", "http://anzymrcvr.appspot.com/receiver/anzymrcvr.html"));
    registerApp(new App("GoogleCastPlayer", "https://www.gstatic.com/eureka/html/gcp.html"));
    registerApp(new App("Fling", "$query"));
    registerApp(new App("TicTacToe", "http://www.gstatic.com/eureka/sample/tictactoe/tictactoe.html",
            new String[] { "com.google.chromecast.demo.tictactoe" }));
}

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 {// w w  w.  ja  v  a 2  s  . co m
        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:com.vuze.android.remote.VuzeEasyTrackerOld.java

@Override
public void registerExceptionReporter(Context applicationContext) {
    ExceptionReporter myHandler = new ExceptionReporter(easyTracker, GAServiceManager.getInstance(),
            Thread.getDefaultUncaughtExceptionHandler(), applicationContext);
    myHandler.setExceptionParser(new ExceptionParser() {
        @Override// ww  w  .  j a v a2s.com
        public String getDescription(String threadName, Throwable t) {
            String s = "*" + t.getClass().getSimpleName() + " " + AndroidUtils.getCompressedStackTrace(t, 0, 9);
            return s;
        }
    });
    Thread.setDefaultUncaughtExceptionHandler(myHandler);
}

From source file:org.adblockplus.android.AdvancedPreferences.java

@Override
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) {
    if (getString(R.string.pref_proxyenabled).equals(key)) {
        final AdblockPlus application = AdblockPlus.getApplication();
        final boolean enabled = sharedPreferences.getBoolean(key, false);
        final boolean serviceRunning = application.isServiceRunning();
        if (enabled) {
            if (!serviceRunning)
                startService(new Intent(this, ProxyService.class));
        } else {//from w ww  .ja  v a  2  s.  c  om
            if (serviceRunning)
                stopService(new Intent(this, ProxyService.class));
            // If disabled, disable filtering as well
            final SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean(getString(R.string.pref_enabled), false);
            editor.commit();
            application.setFilteringEnabled(false);
        }
    }
    if (getString(R.string.pref_refresh).equals(key)) {
        final int refresh = Integer.valueOf(sharedPreferences.getString(key, "0"));
        findPreference(getString(R.string.pref_wifirefresh)).setEnabled(refresh > 0);
    }
    if (getString(R.string.pref_crashreport).equals(key)) {
        final boolean report = sharedPreferences.getBoolean(key,
                getResources().getBoolean(R.bool.def_crashreport));
        try {
            final CrashHandler handler = (CrashHandler) Thread.getDefaultUncaughtExceptionHandler();
            handler.generateReport(report);
        } catch (final ClassCastException e) {
            // ignore - default handler in use
        }
    }
    super.onSharedPreferenceChanged(sharedPreferences, key);
}

From source file:mobisocial.metrics.MusubiExceptionHandler.java

public static void installHandler(Context context) {
    UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
    if (!(currentHandler instanceof MusubiExceptionHandler)) {
        Thread.setDefaultUncaughtExceptionHandler(new MusubiExceptionHandler(context, currentHandler));
    }/* w  w w.j  a  v a2s. c om*/
}

From source file:kr.re.dev.LikeAA.LikeAA.java

@SuppressLint("HandlerLeak")
private void callAfterViews() {
    for (Method method : mAfterViewsMethods) {
        if (!method.isAccessible())
            method.setAccessible(true);//from  w w w.j  a v  a  2s. c om
        final WeakReference<Handler> waekHandler = new WeakReference<Handler>(
                new Handler(Looper.getMainLooper()) {
                    public void dispatchMessage(Message msg) {
                        Object target = mFinder.getTarget();
                        if (target == null)
                            return;
                        Method method = (Method) msg.obj;
                        try {
                            method.invoke(target, makeEmptyArgs(method.getParameterTypes()));
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            Thread.getDefaultUncaughtExceptionHandler()
                                    .uncaughtException(Looper.getMainLooper().getThread(), e);
                        }

                    };
                });
        Message msg = waekHandler.get().obtainMessage();
        msg.obj = method;
        waekHandler.get().sendMessage(msg);
        waekHandler.clear();
    }
}