Android Threads and Throwables
-
07-06-2021 - |
Domanda
I have a class (let's call it ABC) that executes I/O. Some things like FileOutputStream.close make you use try catch blocks around them. In addition, I created my own throwable objects that help the user and me know what is going on.
In the this class I passed in the context of the activity that creates it and made it such that I create and alert dialog box with the throwable text.
So here is my problem I need to run this class off of a new thread, but still want to get the information from the text of the throwable.
So for example this is what a typical catch clause looks like in my class.
new AlertDialog.Builder(myContext)
.setTitle("Error Message")
.setMessage(
"Error Code: #006" + "\n" + T.toString())
.setNeutralButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,
int which) {
// TODO: Add Ability to Email
// Developer
}
}).show();
Would I just do something like
throw new Throwable(throwable);
this inside the ABC class in place of the alert dialog? Then would I move the alert dialog to a try catch where my the Runnable interface run method is called or the do in background for an asynchtask?
Soluzione
Use Java's Thread.UncaughtExceptionHandler to save the text / display a dialog. So you would make a new class extending Thread.UncaughtExceptionHandler, like this:
public class myThreadExceptionHandler implements Thread.UncaughtExceptionHandler
{
private DataTargetClass dataTarget;
public myThreadExceptionHandler(DataTargetClass c)
{
dataTarget = c;
}
public void uncaughtException(Thread t, Throwable e)
{
dataTarget.exceptionObject = e;
dataTarget.onException();
// Just substitute in whatever method your thread uses to return information.
}
}
In your code that started the thread, you would do this:
foo = new DataTargetClass();
Thread t = new Thread(myIoRunnable(foo));
t.setUncaughtExceptionHandler(new myThreadExceptionHandler(foo));
t.start();