gpt4 book ai didi

android - 从父 Activity 中的子 Activity 中捕获异常

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:01:13 26 4
gpt4 key购买 nike

我一直想知道是否有可能通过在父 Activity 中捕获所述崩溃来阻止 Android 应用程序中的崩溃。

假设我在子 Activity 的 onCreate 方法中引发了致命异常,我是否能够以任何方式捕获该异常?或者无论我尝试什么,应用程序都会崩溃吗?

这是我的意思的一个例子:

主.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;
}

这是行不通的。子 Activity 终止并带走父 Activity 。

是否可以通过 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 !!!");
}
});

让我记录未捕获的异常,避免“崩溃”,然而,应用程序黑屏并停止响应...

编辑 2:在线程 How do I obtain crash-data from my Android application? 中阅读了大量内容(感谢 user370305)

我已经到了死胡同,要么我处理 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);
});

最佳答案

Android 中的 Activity 必须独立管理,因为它们有 their own lifecycle .因此,仅在产生异常的 Activity 中捕获异常

如果您的 Activity 需要交互以返回到先前的用户 Activity ,请完成捕获异常的 Activity (子)并让先前的 Activity (父)知道结果。参见 Starting Activities and Getting Results作为一种相互交流父子 Activity 的方法。

关于android - 从父 Activity 中的子 Activity 中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21138680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com