我可以在应用程序崩溃之前调用方法吗?

我是android的新手,当我运行代码时,我总是看到Exception。 所以,有人可以告诉我在应用程序崩溃之前我可以调用一个方法而不需要“try-catch”。

这是处理未捕获exception的更好方法:

public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); appInitialization(); } private void appInitialization() { defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler); } private UncaughtExceptionHandler defaultUEH; // handler listener private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { ex.printStackTrace(); // TODO handle exception here } }; } 

Application是需要维护全局应用程序状态的人的Base类。 因此,在这里处理此类exception将是一个更好的地方。

编辑:上面的代码将处理未捕获的exception,如果它们被抛入UI线程。 如果工作线程中发生exception,您可以通过以下方式处理它:

 private boolean isUIThread(){ return Looper.getMainLooper().getThread() == Thread.currentThread(); } // Setup handler for uncaught exceptions. Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException (Thread thread, Throwable e) { handleUncaughtException (thread, e); } }); public void handleUncaughtException(Thread thread, Throwable e) { e.printStackTrace(); // not all Android versions will print the stack trace automatically if (isUIThread()) { // exception occurred from UI thread invokeSomeActivity(); } else { //handle non UI thread throw uncaught exception new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { invokeSomeActivity(); } }); } } 

我认为你搜索的是UncaughtExceptionHandler。 每当触发exception时都会通知它,并且在通过应用程序冒泡的过程中不会被捕获。

有关在android中实现此function的更多详细信息,请参阅http://www.intertech.com/Blog/android-handling-the-unexpected/ 。

试试这种方式

1)创建类

 import android.content.Context; import android.content.Intent; import android.os.Process; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.Thread.UncaughtExceptionHandler; public class CrashReportHandler implements UncaughtExceptionHandler { public static void attach(Context context) { Thread.setDefaultUncaughtExceptionHandler( new CrashReportHandler(context) ); } ///////////////////////////////////////////// implementation private CrashReportHandler(Context context) { m_context = context; } public void uncaughtException(Thread thread, Throwable exception) { StringWriter stackTrace = new StringWriter(); exception.printStackTrace(new PrintWriter(stackTrace)); //You will get call back here when app crashes. // from RuntimeInit.crash() Process.killProcess(Process.myPid()); System.exit(10); } private Context m_context; } 

如何使用这个课程?

在你的活动onCreate()方法中写下这一行

 CrashReportHandler.attach(this); 

在强制关闭对话框之前有一个名为Uncaught exception的方法,你可以在那里写你的代码..请检查在android上使用全局exception处理

使用CrashLytics为崩溃记者免费且易于实施

https://www.crashlytics.com/