我正在实现Uncaught Exception Handler以跟踪我的应用程序的崩溃报告并向我发送邮件。但是我无法从我的异常处理程序发送邮件。我的Uncaught Exception Handler名称是TopExceptionHandler。我在TopExceptionHandler.java中使用此代码
public class TopExceptionHandler implements Thread.UncaughtExceptionHandler
{
private Thread.UncaughtExceptionHandler defaultUEH;
private Activity app = null;
public TopExceptionHandler(Activity app)
{
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
this.app = app;
}
@Override
public void uncaughtException(Thread t, Throwable e)
{
StackTraceElement[] arr = e.getStackTrace();
String report = e.toString()+"\n\n";
report += "--------- Stack trace ---------\n\n";
for (int i=0; i<arr.length; i++)
{
report += " "+arr[i].toString()+"\n";
}
report += "-------------------------------\n\n";
// If the exception was thrown in a background thread inside
// AsyncTask, then the actual exception can be found with getCause
report += "--------- Cause ---------\n\n";
Throwable cause = e.getCause();
if(cause != null) {
report += cause.toString() + "\n\n";
arr = cause.getStackTrace();
for (int i=0; i<arr.length; i++)
{
report += " "+arr[i].toString()+"\n";
}
}
report += "-------------------------------\n\n";
Log.v("report", report);
try {
FileOutputStream trace = app.openFileOutput(
"stack.trace", Context.MODE_PRIVATE);
trace.write(report.getBytes());
trace.close();
} catch(IOException ioe) {
// ...
}
sendEmail(report);
defaultUEH.uncaughtException(t, e);
}
private void sendEmail(String report)
{
try{
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String subject = "Error report";
String body =
"Mail this to sivaraj@onederr.com: "+
"\n\n"+
report+
"\n\n";
sendIntent.putExtra(Intent.EXTRA_EMAIL,
new String[] {"sivaraj@onederr.com"});
sendIntent.putExtra(Intent.EXTRA_TEXT, report);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "hai");
sendIntent.setType("message/rfc822");
app.startActivity(Intent.createChooser(sendIntent, "Email:"));
}
catch(Exception e)
{
Log.v("sendmail", e.toString());
}
}
@Override
protected void finalize() throws Throwable {
if (Thread.getDefaultUncaughtExceptionHandler().equals(this))
Thread.setDefaultUncaughtExceptionHandler(defaultUEH);
super.finalize();
}
}
CrashreportActivity.java
public class CrashreportActivity extends Activity {
protected TopExceptionHandler mDamageReport = new TopExceptionHandler(this);
String len=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler(this));
for(int i=0;i<len.length();i++)
{
Log.v("error", ""+i);
}
}
}
答案 0 :(得分:0)
当我尝试在uncaughtException体内做某事时,它总是失败。所以我在应用程序关闭后使用AlarmManager引发一个Activity。通过这种方式,您可以发送电子邮件,或者使用邮件内容重新激活您的应用程序,并显示错误并重新启动通知。