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:au.com.cybersearch2.classyjpa.entity.LoaderTaskImpl.java

/**
 * Execute persistence work in  background thread
 * Called on a worker thread to perform the actual load. 
 * @return Boolean object - Boolean.TRUE indicates successful result
 *///  w w  w.j  a  va2  s  .  c  om
@Override
public Boolean loadInBackground() {
    // Hook into UncaughtExceptionHandler chain 
    final UncaughtExceptionHandler chain = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable uncaughtException) { // Save exception for post-execution error handling
            LoaderTaskImpl.this.uncaughtException = uncaughtException;
            chain.uncaughtException(t, uncaughtException);
        }
    });
    return persistenceContainer.executeInBackground(persistenceWork, transactionInfo);
}

From source file:com.application.error.ExceptionHandler.java

/**
 * Register handler for unhandled exceptions.
 * @param context//from  ww w .j ava2 s . c  o m
 */
public static boolean register(Context context) {
    Log.i(TAG, "Registering default exceptions handler");
    // Get information about the Package
    PackageManager pm = context.getPackageManager();
    try {
        PackageInfo pi;
        // Version
        pi = pm.getPackageInfo(context.getPackageName(), 0);
        G.APP_VERSION = pi.versionName;
        // Version Code name
        G.APP_VERSION_CODE = String.valueOf(pi.versionCode);//ADDED VERSION CODE
        // Package name
        G.APP_PACKAGE = pi.packageName;
        // Files dir for storing the stack traces
        G.FILES_PATH = context.getFilesDir().getAbsolutePath();
        // Device model
        G.PHONE_MODEL = android.os.Build.MODEL;
        // Device Size
        try {
            G.PHONE_SIZE = String.valueOf(Utilities.checkDisplaySize());
        } catch (Exception e) {
            G.PHONE_SIZE = "DEVICE SIZE NOT FOUND";
        }
        // 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_VERSION_CODE: " + G.APP_VERSION_CODE);//ADDED VERSION CODE
    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;
    }

    new Thread() {
        @Override
        public void run() {
            // First of all transmit any stack traces that may be lying around
            submitStackTraces();
            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:org.stenerud.kscrash.KSCrash.java

/** Install the crash reporter.
 *
 * @param context The application context.
 *//*from   w  w w.  j  av  a2s. c o  m*/
public void install(Context context) throws IOException {
    String appName = context.getApplicationInfo().processName;
    File installDir = new File(context.getCacheDir().getAbsolutePath(), "KSCrash");
    install(appName, installDir.getCanonicalPath());

    // TODO: Put this elsewhere
    oldUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            KSCrash.this.reportJavaException(e);
            KSCrash.oldUncaughtExceptionHandler.uncaughtException(t, e);
        }
    });
}

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

/**
 * Register handler for unhandled exceptions.
 * @param app /*from w  w  w .  ja  v  a  2  s.c o 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.reallynourl.nourl.fmpfoldermusicplayer.ui.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Thread.currentThread().setName("main");
    Thread.setDefaultUncaughtExceptionHandler(
            new MyUncaughtExceptionHandler(Thread.getDefaultUncaughtExceptionHandler()));
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*w  w w .j av a 2s. c o m*/

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    mCloseSnackBar = Snackbar.make(findViewById(android.R.id.content), "Press again to exit ...",
            Snackbar.LENGTH_SHORT);

    if (MediaManager.getInstance() == null) {
        MediaManager.create(getApplicationContext());
    }

    if (savedInstanceState != null) {
        mActiveContentSavedName = savedInstanceState.getString(SAVED_INSTANCE_FRAGMENT, null);
    }
}

From source file:com.hippo.ehviewer.EhApplication.java

@Override
public void onCreate() {
    // Prepare to catch crash
    mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(this);

    super.onCreate();

    GetText.initialize(this);
    CookieDB.initialize(this);
    StatusCodeException.initialize(this);
    Settings.initialize(this);
    ReadableTime.initialize(this);
    Html.initialize(this);
    AppConfig.initialize(this);
    SpiderDen.initialize(this);
    EhDB.initialize(this);
    EhEngine.initialize();//from w w  w .  j a  va2s . c  om
    BitmapUtils.initialize(this);

    if (EhDB.needMerge()) {
        EhDB.mergeOldDB(this);
    }

    if (Settings.getEnableAnalytics()) {
        Analytics.start(this);
    }

    // Check no media file
    UniFile downloadLocation = Settings.getDownloadLocation();
    if (Settings.getMediaScan()) {
        CommonOperations.removeNoMediaFile(downloadLocation);
    } else {
        CommonOperations.ensureNoMediaFile(downloadLocation);
    }

    // Clear temp dir
    clearTempDir();

    // Check app update
    update();

    // Update version code
    try {
        PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
        Settings.putVersionCode(pi.versionCode);
    } catch (PackageManager.NameNotFoundException e) {
        // Ignore
    }

    if (DEBUG_PRINT_NATIVE_MEMORY || DEBUG_PRINT_IMAGE_COUNT) {
        debugPrint();
    }
}

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.j  a  v a 2s  .  c  om*/
    previousUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(this);
}

From source file:com.dragoniade.deviantart.deviation.SearchRss.java

public List<Deviation> search(ProgressDialog progress, Collection collection) {
    if (user == null) {
        throw new IllegalStateException("You must set the user before searching.");
    }/*  w  w  w.j  a  v  a  2s .com*/
    if (search == null) {
        throw new IllegalStateException("You must set the search type before searching.");
    }
    if (total < 0) {
        progress.setText("Fetching total (0)");
        total = retrieveTotal(progress, collection);
        progress.setText("Total: " + total);
    }

    String searchQuery = search.getSearch().replace("%username%", user);
    String queryString = "http://backend.deviantart.com/rss.xml?q=" + searchQuery
            + (collection == null ? "" : "/" + collection.getId()) + "&type=deviation&offset=" + offset;
    GetMethod method = new GetMethod(queryString);
    List<Deviation> results = new ArrayList<Deviation>(OFFSET);
    try {
        int sc = -1;
        do {
            sc = client.executeMethod(method);
            if (sc != 200) {
                LoggableException ex = new LoggableException(method.getResponseBodyAsString());
                Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), ex);

                int res = DialogHelper.showConfirmDialog(owner,
                        "An error has occured when contacting deviantART : error " + sc + ". Try again?",
                        "Continue?", JOptionPane.YES_NO_OPTION);
                if (res == JOptionPane.NO_OPTION) {
                    return null;
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                }
            }
        } while (sc != 200);

        XmlToolkit toolkit = XmlToolkit.getInstance();

        Element responses = toolkit.parseDocument(method.getResponseBodyAsStream());
        method.releaseConnection();

        HashMap<String, String> prefixes = new HashMap<String, String>();
        prefixes.put("media", responses.getOwnerDocument().lookupNamespaceURI("media"));
        NamespaceContext context = toolkit.getNamespaceContext(prefixes);

        List<?> deviations = toolkit.getMultipleNodes(responses, "channel/item");
        if (deviations.size() == 0) {
            return results;
        }

        for (Object obj : deviations) {
            Element deviation = (Element) obj;

            Deviation da = new Deviation();
            da.setId(getId(toolkit.getNodeAsString(deviation, "guid")));
            da.setArtist(toolkit.getNodeAsString(deviation, "media:credit", context));
            da.setCategory(toolkit.getNodeAsString(deviation, "media:category", context));
            da.setTitle(toolkit.getNodeAsString(deviation, "media:title", context));
            da.setUrl(toolkit.getNodeAsString(deviation, "link"));
            da.setTimestamp(parseDate(toolkit.getNodeAsString(deviation, "pubDate")));
            da.setMature(!"nonadult".equals(toolkit.getNodeAsString(deviation, "media:rating", context)));
            da.setCollection(collection);

            Element documentNode = (Element) toolkit.getSingleNode(deviation,
                    "media:content[@medium='document']", context);
            Element imageNode = (Element) toolkit.getSingleNode(deviation, "media:content[@medium='image']",
                    context);
            Element videoNode = (Element) toolkit.getSingleNode(deviation, "media:content[@medium='video']",
                    context);

            if (imageNode != null) {
                String content = imageNode.getAttribute("url");
                String filename = Deviation.extractFilename(content);
                da.setImageDownloadUrl(content);
                da.setImageFilename(filename);

                da.setResolution(imageNode.getAttribute("width") + "x" + imageNode.getAttribute("height"));
            }

            if (documentNode != null) {
                String content = documentNode.getAttribute("url");
                String filename = Deviation.extractFilename(content);
                da.setDocumentDownloadUrl(content);
                da.setDocumentFilename(filename);
            }

            if (videoNode != null) {
                String content = videoNode.getAttribute("url");
                if (!content.endsWith("/")) {
                    content = content + "/";
                }
                String filename = Deviation.extractFilename(content);
                da.setDocumentDownloadUrl(content);
                da.setDocumentFilename(filename);
            }

            results.add(da);
        }
        offset = offset + deviations.size();
        return results;
    } catch (HttpException e) {
        DialogHelper.showMessageDialog(owner, "Error contacting deviantART : " + e.getMessage() + ".", "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    } catch (IOException e) {
        DialogHelper.showMessageDialog(owner, "Error contacting deviantART : " + e.getMessage() + ".", "Error",
                JOptionPane.ERROR_MESSAGE);
        return null;
    }
}

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 w w.j a  va  2  s .  com
        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: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   w  w  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;
}