<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Global Exception Handler &#8211; Pauls Blog</title>
	<atom:link href="https://sterl.org/tag/global-exception-handler/feed/" rel="self" type="application/rss+xml" />
	<link>https://sterl.org</link>
	<description></description>
	<lastBuildDate>Fri, 20 Sep 2019 14:43:45 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
	<item>
		<title>Android Global Exception Handler</title>
		<link>https://sterl.org/2016/02/android-global-exception-handler/</link>
					<comments>https://sterl.org/2016/02/android-global-exception-handler/#comments</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Fri, 12 Feb 2016 14:51:43 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Global Exception Handler]]></category>
		<category><![CDATA[UncaughtExceptionHandler]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=136</guid>

					<description><![CDATA[Background / Motivation Sometimes it is quite useful to handle/catch exceptions in a central handler. Typical samples are: Handle Authorization problems e.g. with your backend Central dispatching of these error to an Exception Collector like Crashlytics (ur just send an email) Just show a message dialog to the user Implementation Just creating an Exception is&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Background / Motivation</h2>



<p>Sometimes it is quite useful to handle/catch exceptions in a central <code>handler</code>. Typical samples are:</p>



<ul class="wp-block-list"><li>Handle Authorization problems e.g. with your backend</li><li>Central dispatching of these error to an Exception Collector like Crashlytics (ur just send an email)</li><li>Just show a message dialog to the user</li></ul>



<h2 class="wp-block-heading">Implementation</h2>



<p>Just creating an Exception is straight forward <code>java.lang.Thread.UncaughtExceptionHandler</code>. The little more tricky part is integrating it into an Android application. Two obvious ways we might choose from:</p>



<ul class="wp-block-list"><li>Attach the Exception Handler in the Application <ul><li>Can&#8217;t open UI Dialogs or other Activities properly</li><li>Will be executed for any activity </li></ul></li><li>Attach the Exception Handler in an Activity <ul><li>May start other activities</li><li>Needs a Base class to be applied in an easy way to all activities </li></ul></li></ul>



<h3 class="wp-block-heading">Exception as Application Handler</h3>



<p>Typical here is to log the exception and later on send it to the backend, e.g. after the application was restarted.</p>



<p>This sample code just logs each exception into a file, which we can later on inspect and send to the backend if we like.</p>



<h4 class="wp-block-heading">Exception Handler</h4>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public class LoggingExceptionHandler implements Thread.UncaughtExceptionHandler {
    private final static String TAG = LoggingExceptionHandler.class.getSimpleName();
    private final static String ERROR_FILE = MyAuthException.class.getSimpleName() + &quot;.error&quot;;

    private final Context context;
    private final Thread.UncaughtExceptionHandler rootHandler;

    public LoggingExceptionHandler(Context context) {
        this.context = context;
        // we should store the current exception handler -- to invoke it for all not handled exceptions ...
        rootHandler = Thread.getDefaultUncaughtExceptionHandler();
        // we replace the exception handler now with us -- we will properly dispatch the exceptions ...
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(final Thread thread, final Throwable ex) {
        try {
            Log.d(TAG, &quot;called for &quot; + ex.getClass());
            // assume we would write each error in one file ...
            File f = new File(context.getFilesDir(), ERROR_FILE);
            // log this exception ...
            FileUtils.writeStringToFile(f, ex.getClass().getSimpleName() + &quot; &quot; + System.currentTimeMillis() + &quot;\n&quot;, true);
        } catch (Exception e) {
            Log.e(TAG, &quot;Exception Logger failed!&quot;, e);
        }

    public static final List&lt;String&gt; readExceptions(Context context) {
        List&lt;String&gt; exceptions = new ArrayList&lt;&gt;();
        File f = new File(context.getFilesDir(), ERROR_FILE);
        if (f.exists()) {
            try {
                exceptions = FileUtils.readLines(f);
            } catch (IOException e) {
                Log.e(TAG, &quot;readExceptions failed!&quot;, e);
            }
        }
        return exceptions;
    }
}</pre></div>



<h4 class="wp-block-heading"> Activation of the Exception Handler </h4>



<p>We need now only to attach it once in our Application:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        new LoggingExceptionHandler(this);
    }
}</pre></div>



<h4 class="wp-block-heading">Enable the Android Application </h4>



<p>And of course make sure it is attached in our <code>AndroidManifest.xml</code>. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;htmlmixed&quot;,&quot;mime&quot;:&quot;text/html&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;HTML&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;html&quot;}">&lt;application
    android:name=&quot;.MyApp&quot;</pre></div>



<h3 class="wp-block-heading"> Exception Handler in an Activity </h3>



<p>Attaching an exception handler in the activity allows us to do a little more, most important here starting a different activity work &#8212; in the case of the <code>ApplicationContext</code> it would just hang. </p>



<h4 class="wp-block-heading">Exception Handler</h4>



<p>In this case, we check the exceptions if we could gracefully handle them. If so the start the appropriate activity and could pass more informations to it if needed. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {

    public static final String EXTRA_MY_EXCEPTION_HANDLER = &quot;EXTRA_MY_EXCEPTION_HANDLER&quot;;
    private final Activity context;
    private final Thread.UncaughtExceptionHandler rootHandler;

    public MyExceptionHandler(Activity context) {
        this.context = context;
        // we should store the current exception handler -- to invoke it for all not handled exceptions ...
        rootHandler = Thread.getDefaultUncaughtExceptionHandler();
        // we replace the exception handler now with us -- we will properly dispatch the exceptions ...
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(final Thread thread, final Throwable ex) {
        if (ex instanceof MyAuthException) {
            // note we can't just open in Android an dialog etc. we have to use Intents here
            // http://stackoverflow.com/questions/13416879/show-a-dialog-in-thread-setdefaultuncaughtexceptionhandler

            Intent registerActivity = new Intent(context, AuthActivity.class);
            registerActivity.putExtra(EXTRA_MY_EXCEPTION_HANDLER, MyExceptionHandler.class.getName());
            registerActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            registerActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);

            context.startActivity(registerActivity);
            // make sure we die, otherwise the app will hang ...
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        } else {
            rootHandler.uncaughtException(thread, ex);
        }
    }
}</pre></div>



<h4 class="wp-block-heading">Activation of the Exception Handler</h4>



<p>Now it gets a little more messy. As we need to activate/init this handler with an Activity we have to ensure that either in each Activity or we provide a base activity all other inherit from. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-eclipse" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;htmlmixed&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;eclipse&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public abstract class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new MyExceptionHandler(BaseActivity.this);
    }
}</pre></div>



<h3 class="wp-block-heading">Sample Code on Github</h3>



<p><a href="https://github.com/puel/training/tree/master/android/GlobalExceptionHandler" target="_blank" rel="noreferrer noopener">Sample code on GitHub</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2016/02/android-global-exception-handler/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
