Is it possible to create some sort of global exception handler in Android?

大城市里の小女人 提交于 2019-12-01 09:18:26

问题


My application includes a series of Activities, through which the user must proceed in a linear fashion. Let's say that this series of activities looks like this: A (represents the main menu), B, C, D, E. The user proceeds like this: A -> B -> C -> D -> E. In each of these activities, the user must either input data or allow the device to get the data automatically (e.g. via the network or Bluetooth).

Occasionally, my app crashes in one of the middle activities. What ends up happening, typically, is that the app moves back an activity or two. For example, if my app crashes in Activity D, the app might move back to Activity C or B. But the problem is, after such a crash, the input data is in such a weird state that the app again crashes and shows the force close dialog, all the way back to Activity A, the main menu.

How can I catch these exceptions that cause these crashes globally throughout the application, so I can clean up the data and gracefully allow the user to return to the main menu?


回答1:


Extend Application class

import android.app.Application;
import android.util.Log;

public class MyApplication extends Application {

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

            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                Log.e("MyApplication", ex.getMessage());            

            }
        });
    }
}

Add the following line in AndroidManifest.xml file as Application attribute

android:name=".MyApplication"



回答2:


    Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler()... );


来源:https://stackoverflow.com/questions/6904684/is-it-possible-to-create-some-sort-of-global-exception-handler-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!