2016-05-30 84 views
0

上执行uncaughtException现在,我试试这个。只有连接摄像头服务失败,请在android

MainActivity.java

Thread.setDefaultUncaughtExceptionHandler(new UncaughtException(MainActivity.this)); 

UncaughtException.class

public class UncaughtException implements Thread.UncaughtExceptionHandler { 
private Context context; 
private static Context context1; 

public UncaughtException(Context ctx) { 
    context = ctx; 
    context1 = ctx; 
} 

public void uncaughtException(Thread t, Throwable e){ 
    try { 
     StringBuilder report =new StringBuilder(); 
     sendErrorMail(report); 
    } catch (Throwable ignore) { 
     Log.e(UncaughtException.class.getName(), 
       "Error while sending error e-mail", ignore); 
    } 
} 

public void sendErrorMail(final StringBuilder errorContent) { 
    final AlertDialog.Builder builder = new AlertDialog.Builder(context); 
    new Thread() { 
     @Override 
     public void run() { 
      Looper.prepare(); 
      builder.setTitle("sorry."); 
      builder.create(); 
      builder.setNegativeButton("Cancel", 
        new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          System.exit(0); 
         } 
        }); 
      builder.setMessage("OoOopps, Your application has crashed"); 
      builder.show(); 
      Looper.loop(); 
         } 
     }.start(); 
     } 
    } 

这个好工作。

但这一切都发生异常显示对话框。

我想只发生`未能连接到摄像头服务'异常,显示对话框。

换句话说,如果我的设备没有连接摄像头,显示对话框。 (不是应用程序停止消息)。

回答

0

您可以在try catch块中打开相机功能,并捕获要显示的异常显示警报。

在开放式相机捕捉异常将导致相机相关的异常不会传递给未捕获的异常类和“哎呀应用程序崩溃”警报不会去显示。

try { 
      myCamera = Camera.open(); 

     } catch (Exception e) { 

     //Here you catch: Failed to connect to camera service and display alert 
     } 
+0

谢谢,但是,我不明白。你建议捕捉相机异常? – chohyunwook

+0

查看更新的答案我已经添加了代码片段 –

+0

您应该在这种情况下始终捕获您首先知道的异常。 UngoughtExceptionHandler更像是第二个安全网,它可以捕获您可能已经遗忘的异常。 –