当我的android应用程序抛出异常时,我想显示一个自定义对话框告诉用户发生了错误,所以我使用Thread.setDefaultUncaughtExceptionHandler
来设置一个全局异常处理程序:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, final Throwable ex) {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle("There is something wrong")
.setMessage("Application will exit:" + ex.toString())
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// throw it again
throw (RuntimeException) ex;
}
})
.show();
}
});
}
}
但我发现它抛出了任何异常,AlertDialog
将不会显示,而应用程序会阻塞,过一会儿,它会显示一个系统对话框:
X app is not responding. Would you like to close it?
Wait | OK
我现在该怎么办?
更新
日志:
11-16 12:54:16.017: WARN/WindowManager(90): Attempted to add window with non-application token WindowToken{b38bb6a8 token=null}. Aborting.
似乎错误来自new AlertDialog.Builder(getApplicationContext());
但这是Application
子类中的异常处理程序,如何为其设置活动实例?
答案 0 :(得分:29)
您无法从此处执行任何UI操作。只需启动另一个活动/启动画面。传递额外的意图以表示该活动中的崩溃和显示对话框。
/*
* (non-Javadoc)
*
* @see
* java.lang.Thread.UncaughtExceptionHandler#uncaughtException(java.
* lang.Thread, java.lang.Throwable)
*/
@Override
public void uncaughtException(Thread t, final Throwable e) {
StackTraceElement[] arr = e.getStackTrace();
final StringBuffer report = new StringBuffer(e.toString());
final String lineSeperator = "-------------------------------\n\n";
report.append(DOUBLE_LINE_SEP);
report.append("--------- Stack trace ---------\n\n");
for (int i = 0; i < arr.length; i++) {
report.append( " ");
report.append(arr[i].toString());
report.append(SINGLE_LINE_SEP);
}
report.append(lineSeperator);
// If the exception was thrown in a background thread inside
// AsyncTask, then the actual exception can be found with getCause
report.append("--------- Cause ---------\n\n");
Throwable cause = e.getCause();
if (cause != null) {
report.append(cause.toString());
report.append(DOUBLE_LINE_SEP);
arr = cause.getStackTrace();
for (int i = 0; i < arr.length; i++) {
report.append(" ");
report.append(arr[i].toString());
report.append(SINGLE_LINE_SEP);
}
}
// Getting the Device brand,model and sdk verion details.
report.append(lineSeperator);
report.append("--------- Device ---------\n\n");
report.append("Brand: ");
report.append(Build.BRAND);
report.append(SINGLE_LINE_SEP);
report.append("Device: ");
report.append(Build.DEVICE);
report.append(SINGLE_LINE_SEP);
report.append("Model: ");
report.append(Build.MODEL);
report.append(SINGLE_LINE_SEP);
report.append("Id: ");
report.append(Build.ID);
report.append(SINGLE_LINE_SEP);
report.append("Product: ");
report.append(Build.PRODUCT);
report.append(SINGLE_LINE_SEP);
report.append(lineSeperator);
report.append("--------- Firmware ---------\n\n");
report.append("SDK: ");
report.append(Build.VERSION.SDK);
report.append(SINGLE_LINE_SEP);
report.append("Release: ");
report.append(Build.VERSION.RELEASE);
report.append(SINGLE_LINE_SEP);
report.append("Incremental: ");
report.append(Build.VERSION.INCREMENTAL);
report.append(SINGLE_LINE_SEP);
report.append(lineSeperator);
Log.e("Report ::", report.toString());
Intent crashedIntent = new Intent(BaseActivity.this, SplashActivity.class);
crashedIntent.putExtra(EXTRA_CRASHED_FLAG, "Unexpected Error occurred.");
crashedIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
crashedIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(crashedIntent);
System.exit(0);
// If you don't kill the VM here the app goes into limbo
}
另见:
Android UncaughtExceptionHandler that instantiates an AlertDialog breaks
Toast not showing up in UnCaughtExceptionHandler
How to start activity from UncaughtExceptionHandler if this is main thread crashed?
我是怎么做的:
我有一个扩展Activity的BaseActivity,并且在活动的onCreate中我设置了UncaughtExceptionHandler。我的所有活动都扩展了BaseActivity而不是Activity。
<强>键强>
Application.onCreate
中设置例外处理程序,而应创建BaseActivity
并将其设置在onCreate
方法上。System.exit(0)
SplashActivity
,因为它会被销毁,相反,我们可以传递一些错误消息或将其保留在文件中。答案 1 :(得分:5)
似乎提供的解决方案不起作用(至少对于Android 4.0及更高版本)。对于可能感兴趣的任何人,都无法打开Activity
或涉及某些UI
元素,例如Dialogs
。经过一些研究后,我意识到您可以提供的最大值是Toast
消息,通知日志传送到服务器。可选地,SharedPreferences
可用于指示应用程序崩溃,并且在应用程序重新启动时,可以基于Dialog
属性值显示SharedPreferences
,并从那里传递先前捕获的异常(显然阿克拉使用相同的方法):
public class FirstAc extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView();
sharedPrefValue = pref.getBoolean("DID_APP_CRASH", false);
if(sharedPrefValue)
dialog.show();
}
}
当应用程序与以下代码段崩溃时,异常可以保存为字符串:
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
String stStr = sw.toString();
prefEditor.putString("EXCEPTION_CAUGHT", stStr);
总而言之,为了将未捕获的异常传递到远程服务器,请创建自定义UncaughtExceptionHandler
,最重要的是保留对默认UncaughtExceptionHandler
的引用。通过调用System.exit()
而不是突然关闭VM,让Android在执行自定义操作后处理异常更为合理。我更喜欢在Application
端设置异常处理程序:
public class CustomApp extends Application {
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(this));
}
}
在执行自定义行为后的CustomExceptionHandler
内,让Android以默认方式处理异常:
public class CustomExceptionHandler implements UncaughtExceptionHandler {
private CustomApp _app;
private UncaughtExceptionHandler _defaultEH;
public YolbilExceptionHandler(YolbilApp ac){
_defaultEH = Thread.getDefaultUncaughtExceptionHandler();
_app = ac;
}
@Override
public void uncaughtException(Thread thread, final Throwable ex) {
Toast.makeText(_app, "Delivering log...", Toast.LENGTH_LONG).show();
// obtain the Exception info as a String
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String exStr = sw.toString();
ExceptionServer.getInstance().deliverMessageAsync(exStr, _app);
_defaultEH.uncaughtException(thread, ex);
}
}
以下是如何将消息异步传递到服务器的示例:
public void deliverMessageAsync(final String msg, final YolbilApp app){
new Thread(new Runnable() {
@Override
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(SERVER_ADDR);
try {
Looper.prepare();
Toast.makeText(app, R.string.msg_delivering_log, Toast.LENGTH_LONG).show();
httppost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
httpclient.execute(httppost);
Toast.makeText(app, "Log delivered ...", Toast.LENGTH_SHORT).show();
Looper.loop();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}