我正试图在我的任何活动中检查未捕获的异常。
我把这段代码放在onCreate
之后:
Thread.setDefaultUncaughtExceptionHandler(
new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
ex.printStackTrace();
Utils.logError(MainActivity.this,session);
}
});
Utils.logError
方法将logCat内容写入文本文件,然后使用自定义AsyncTask上传到FTP服务器。
这是logError方法代码
public static void logError(final Context ctx,final SessionManager session){
StringBuilder log=new StringBuilder();
try {
(... code that read logCat and write to a file ...)
//Upload result file to FTP with a AsyncTask
new Thread(new Runnable() {
public void run() {
if(Utils.isInternetConn(ctx)){
FTPHandler ftp = null;
ArrayList<File> archivosAcargar = new ArrayList<File>();
archivosAcargar.add(file);
ftp = new FTPHandler(ctx,archivosAcargar,session.getCodUser());
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
if(ftp.ftpConnect("server","user" ,"pass" ,21)){
ftp.execute("upload");
}
}
}
}).start();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
AsyncTask代码
修改
@Override
protected String doInBackground(String... peticion) {
String res="";
if(peticion[0].equals("upload")){
if(ftpUpload()) res = "Done upload";
else res = "Error upload";
}
//This print shows "Done upload"
System.out.println(res);
return res;
}
@Override
protected void onPostExecute(String response) {
//This print not executes
System.out.println("Response " + "/" + response + "/");
if(response.equals("Done upload"))
{
System.out.println("done");
if(!isLog){ mDialog.dismiss();
//Toast
}
else{
System.exit(1);
}
}
if(response.equals("Error upload"))
{
if(!isLog)mDialog.dismiss();
}
}
问题是AsyncTask已完成且文件已上传,(@Override) onPostExecute
永远不会被调用。
我试图在没有例外的情况下调用Utils.logError
并且工作正常但是如果我强制例外不起作用。
任何人都可以帮助我吗?