Gra*_*tzi 58 android exception-handling
是否有代码示例或有关如何使用该Thread.setDefaultUncaughtExceptionHandler方法的教程?基本上我在我的应用程序中尝试在抛出异常时显示自定义警报对话框.是否有可能做到这一点?我知道在屏幕上显示某些内容有点棘手,如果在UI线程中抛出异常,但我不知道任何解决方法.
Cod*_*ife 75
使用解决方案来到此页面的人的基本示例:)
public class ChildActivity extends BaseActivity {
@SuppressWarnings("unused")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int a=1/0;
}
}
Run Code Online (Sandbox Code Playgroud)
处理错误的类别:
public class BaseActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
Log.e("Alert","Lets See if it Works !!!");
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*Sam 34
码:
public class BaseActivity extends Activity {
@Override
public void onCreate() {
super.onCreate();
final Thread.UncaughtExceptionHandler oldHandler =
Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(
Thread paramThread,
Throwable paramThrowable
) {
//Do your own error handling here
if (oldHandler != null)
oldHandler.uncaughtException(
paramThread,
paramThrowable
); //Delegates to Android's error handling
else
System.exit(2); //Prevents the service/app from freezing
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
对于那些只想在您的应用程序在设备上崩溃时(在调试配置中)查看异常详细信息的人。这是应用程序类:
private Thread.UncaughtExceptionHandler oldHandler;
@Override
public void onCreate() {
super.onCreate();
if (!BuildConfig.DEBUG)
return;
oldHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
try {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
Intent intent = new Intent(Intent.ACTION_SEND);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_TEXT, sw.toString());
intent.setType("text/plain");
startActivity(intent);
} catch(Exception ex) {
ex.printStackTrace();
} finally {
if (oldHandler != null)
oldHandler.uncaughtException(t, e);
else
System.exit(1);
}
});
}
Run Code Online (Sandbox Code Playgroud)
它使用外部应用程序,因为您的 UI 线程可能不再工作。
| 归档时间: |
|
| 查看次数: |
53012 次 |
| 最近记录: |