【发布时间】:2014-02-03 23:54:36
【问题描述】:
我一直想知道是否可以通过捕获父 Activity 中的崩溃来阻止 Android 应用中的崩溃。
假设我在子活动的 onCreate 方法中导致了致命异常,我是否能够捕获该异常?还是不管我怎么尝试,应用都会崩溃?
这是我的意思的一个例子:
Main.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ly_main);
// My Main activity starts
try{
// Call the next activity
Intent intent = new Intent(getApplicationContext(), Child.class);
startActivity(intent);
}catch(Exception e){
Log.wtf("Exception_WTF","Exception from child activity woohoo \n "+ e.toString());
}
子.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ly_child);
// Create exception... for science
int a = 0;
a = 1/a;
}
这不起作用。子活动死亡并带走父母。
是否可以通过 startActivityForResult 来实现?
谢谢,
编辑:我不需要崩溃数据,我只想知道如何避免应用崩溃。
环顾四周,我发现: Using Global Exception Handling on android
其中包括这件作品:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
Log.e("Alert","Lets See if it Works !!!");
}
});
那让我记录下 uncaughtException,避免“崩溃”,但是,应用程序黑屏并停止响应...
编辑 2: 经过大量阅读(感谢user370305)线程How do I obtain crash-data from my Android application?
我已经走到了死胡同,要么我处理 uncaughtException 并调用 defaultUEH.uncaughtException(paramThread, paramThrowable);所以应用程序崩溃,或者我不调用defaultUEH.uncaughtException,应用程序不会崩溃,但也不响应...... 有什么想法吗?
final Thread.UncaughtExceptionHandler defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
Log.e("Alert","Lets See if it Works !!!");
defaultUEH.uncaughtException(paramThread, paramThrowable);
});
【问题讨论】:
-
是的,这是可能的,期望是可序列化的,因此它们可以放在一个包中
-
Activity 是独立的,Intent 通信是异步的。也许你可以探索startActivityForResult的方式。
-
Startactivity 不起作用
-
您可以通过一些创意来做到这一点。给我几天,我会发布一些代码(大忙人)。
标签: android