如何防止Android应用程序崩溃

时间:2017-10-03 07:26:39

标签: android exception-handling crash

我想阻止我的应用因某些异常而崩溃。我希望异常存储在日志和应用程序中不崩溃。因为它给用户留下了不好的印象。我如何实现这一目标?

3 个答案:

答案 0 :(得分:5)

为此你需要两个类只需复制粘贴它们。 当您的应用程序中发生任何异常时,将调用此类。

public class CrashHandler implements
        java.lang.Thread.UncaughtExceptionHandler {
    private final Context myContext;
    private final String LINE_SEPARATOR = "\n";

    public CrashHandler(Context context) {
        myContext = context;
    }

    public void uncaughtException(Thread thread, Throwable exception) {
        StringWriter stackTrace = new StringWriter();
        exception.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);

        Intent intent = new Intent(myContext, ExceptionDisplay.class);
        intent.putExtra("error", errorReport.toString());
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        myContext.startActivity(intent);

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

}

现在制作一个显示错误的活动: -

public class ExceptionDisplay extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.exception_display_layout);

        TextView exception_text = (TextView) findViewById(R.id.exception_text);
        Button btnBack = (Button) findViewById(R.id.btnBack);
        exception_text.setText(getIntent().getExtras().getString("error"));

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intentData();
            }
        });
    }

    @Override
    public void onBackPressed() {
        intentData();
    }

    public void intentData() {

        Log.d("CDA", "onBackPressed Called");
        Intent setIntent = new Intent(ExceptionDisplay.this, AppDataSourceSelection.class);
        setIntent.addCategory(Intent.CATEGORY_HOME);
        setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(setIntent);
    }
}

现在,您可以通过扩展应用程序类的类来调用此类:

public class ErrorHandler extends Application {


    @Override
    public void onCreate() {
        super.onCreate();
       Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(getApplicationContext()));

        }}

答案 1 :(得分:2)

您可以自己处理未捕获的异常。 将以下代码用于您的应用程序类。

public class MyApplication extends Application {
    private UncaughtExceptionHandler defaultUEH;

    private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler =
        new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {

                // here I do logging of exception to a db
                Log.d("MyApp", "Uncaught exception.");     
               // Do what you want.

              // re-throw exception to O.S. if that is serious and need to be handled by o.s. Uncomment the next line that time.
            //defaultUEH.uncaughtException(thread, ex);
            }
        };

    public MyApplication() {
        defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

        // setup Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
    }
}

答案 2 :(得分:1)

您可以使用try catch块来捕获异常,这样可以防止应用程序崩溃。在catch块中获取预期的异常并记录下来以获得帮助。 但请记住并非每个例外都可以被捕获 因为某些例外不是来自例外 - 例如可投掷和错误。

基本上,类型层次结构是:

   Object
     |
  Throwable
   /       \
Exception  Error

只能抛出Throwables和派生类,所以如果你抓住Throwable,那真的会抓住所有东西。

从Exception(或Exception本身)派生的异常(除了从RuntimeException派生的异常)计为已检查的异常 - 它们是您必须声明要抛出的异常,或者如果您调用抛出它们的东西则捕获。< / p>

总而言之,Java异常层次结构有点乱......