2012-05-10 28 views
1

我有一个类(姑且称之为ABC)执行I/O。一些像FileOutputStream.close这样的东西让你在它们周围使用try catch块。另外,我创建了自己的可抛物体,帮助用户和我知道发生了什么。Android的线程和将Throwable

在这个类我创建它的活动的情况下通过,并使其这样的,我创建并与抛出文本警告对话框。

因此,这里是我的问题,我需要运行这个班级一个新的线程,但仍然希望得到来自抛出的文本信息。

因此,例如,这是一个典型的catch子句的样子在我的课。

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

请问我只是做类似

throw new Throwable(throwable); 

这个ABC类中到位的警告对话框中的?然后,我会移动警报对话框来试试抓在我的Runnable接口的run方法被调用或一个asynchtask在后台做?

回答

2

使用Java的Thread.UncaughtExceptionHandler保存文本/显示一个对话框。所以,你会做一个新的类扩展Thread.UncaughtExceptionHandler,像这样:

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. 
    } 
} 

在你的代码,启动线程,你可以这样做:

foo = new DataTargetClass(); 
Thread t = new Thread(myIoRunnable(foo)); 
t.setUncaughtExceptionHandler(new myThreadExceptionHandler(foo)); 
t.start();