People,
I will catch unhandled exceptions for Android with a piece of code like this at the top of onCreate:
try { File crashLogDirectory = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + Constants.CrashLogDirectory); crashLogDirectory.mkdirs(); Thread.setDefaultUncaughtExceptionHandler(new RemoteUploadExceptionHandler( this, crashLogDirectory.getCanonicalPath())); } catch (Exception e) { if (MyActivity.WARN) Log.e(ScruffActivity.TAG, "Exception setting up exception handler! " + e.toString()); }
I would like to come up with something similar for about two dozen AsyncTasks that I use in my Android application, so the unhandled exceptions that occur in doInBackground get caught and logged.
The problem is that AsyncTask accepts any type of initializers, I'm not sure how to declare a superclass from which all my AsyncTasks inherits, which sets this unhandled exception handler.
Can anyone recommend a good design pattern for handling unhandled exceptions in the doInBackground AsyncTask method, which does not require copying and pasting the code like above for each new AsyncTask definition?
Thanks!
UPDATE
Here is the design pattern I used after a closer look at the AsyncTask source
import java.io.File; import android.content.Context; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; public abstract class LoggingAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> { protected void setupUnhandledExceptionLogging(Context context) { try { File crashLogDirectory = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + Constants.CrashLogDirectory); crashLogDirectory.mkdirs(); Thread.setDefaultUncaughtExceptionHandler(new RemoteUploadExceptionHandler( context, crashLogDirectory.getCanonicalPath())); } catch (Exception e) { if (MyActivity.WARN) Log.e(ScruffActivity.TAG, "Exception setting up exception handler! " + e.toString()); } } }
Then I define my tasks as follows:
private class MyTask extends LoggingAsyncTask<Void, Void, HashMap<String, Object>> { protected HashMap<String, Object> doInBackground(Void... args) { this.setupUnhandledExceptionLogging(MyActivity.this.mContext);
Obviously, your task can accept any parameters necessary for this template. For you, you need to define RemoteUploadExceptionHandler to perform the necessary registration / loading.
java android exception android-asynctask unhandled-exception
esilver
source share