捕获错误和用户信息

时间:2014-05-06 05:32:15

标签: android

我遇到问题,因为我的应用程序在后台运行,有时会发生关闭它的错误。如何在任何活动或服务中捕获错误以播放声音并在通知栏上添加信息?

2 个答案:

答案 0 :(得分:2)

要解决此问题,可以使用uncaughtExceptionHandler接口。

public class ExceptionHandler implements UncaughtExceptionHandler{

Utils utils ;
Context context;
private final String LINE_SEPARATOR = "\n";

public ExceptionHandler(Context con) {
    // TODO Auto-generated constructor stub
    context = con;
}

@Override
public void uncaughtException(Thread arg0, Throwable arg1) {
    // TODO Auto-generated method stub

    StringWriter stackTrace = new StringWriter();
    arg1.printStackTrace(new PrintWriter(stackTrace));
    StringBuilder errorReport = new StringBuilder();
    errorReport.append("************ CAUSE OF ERROR ************\n\n");
    errorReport.append(stackTrace.toString());

    errorReport.append("\n************ DEVICE INFORMATION ***********\n");
    errorReport.append("Brand: ");
    errorReport.append(Build.BRAND);
    errorReport.append(LINE_SEPARATOR);
    errorReport.append("Device: ");
    errorReport.append(Build.DEVICE);
    errorReport.append(LINE_SEPARATOR);
    errorReport.append("Model: ");
    errorReport.append(Build.MODEL);
    errorReport.append(LINE_SEPARATOR);
    errorReport.append("Id: ");
    errorReport.append(Build.ID);
    errorReport.append(LINE_SEPARATOR);
    errorReport.append("Product: ");
    errorReport.append(Build.PRODUCT);
    errorReport.append(LINE_SEPARATOR);
    errorReport.append("\n************ FIRMWARE ************\n");
    errorReport.append("SDK: ");
    errorReport.append(Build.VERSION.SDK);
    errorReport.append(LINE_SEPARATOR);
    errorReport.append("Release: ");
    errorReport.append(Build.VERSION.RELEASE);
    errorReport.append(LINE_SEPARATOR);
    errorReport.append("Incremental: ");
    errorReport.append(Build.VERSION.INCREMENTAL);
    errorReport.append(LINE_SEPARATOR);


    //after this you can do whatever you want , like i start an activity and show error log there


 Intent i = new Intent(context,ExceptionActivity.class);
        i.putExtra("exception",errorReport.toString());
        context.startActivity(i);


        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(10);





    }
    }

并添加此行

Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

在每个活动中(未捕获的异常可以引发)

答案 1 :(得分:0)

在Oncreate方法中使用未捕获的异常处理程序

Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                ex.printStackTrace();
                Log.e(TAG, "Uncaught Exception "+ex);
                            //Habdle your exception here. 

                System.exit(2);
                android.os.Process.killProcess(android.os.Process.myPid()); 
            }
        });