我使用此代码创建应用程序数据文件夹
内容的zippublic static void zipFolder(File inputFolder) {
try {
File srcFile = inputFolder;
File[] files = srcFile.listFiles();
FileOutputStream fos = new FileOutputStream(new File(inputFolder, "toSend.zip"));
ZipOutputStream zos = new ZipOutputStream(fos);
Log.d("", "Zip directory: " + srcFile.getName());
for (File file : files) {
Log.d("", "Adding file: " + file.getName());
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(file);
zos.putNextEntry(new ZipEntry(file.getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
zos.close();
fos.close();
} catch (IOException ioe) {
Log.e("", ioe.getMessage());
}
}
在常规代码中调用它时工作正常,但是我希望在应用程序与其他日志代码崩溃时运行此代码我在重写的Thread.UncaughtExceptionHandler中运行
在这种情况下,文件已创建,但它会无限增长,直到我强行关闭应用程序
当跟随调试器的流程时,我看到正在压缩的文件(File []文件)正是我期望的那些,并且我设法退出函数调用(打开以执行以下代码)所以我不会&#39 ;认为它的功能属于无限循环
public class MyApplication extends Application {
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
//here and anywhere else in the code it manages to create a valid zip file with the folder contents
File toZip = getExternalFilesDir(null);
MyUtils.zipFolder(toZip);
if (Costanti.SETTINGS_MAKE_CRASH_LOG)
Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
{
@Override
public void uncaughtException (Thread thread, Throwable e)
{
e.printStackTrace();
File logFolder = getExternalFilesDir(null);
Log.d("Dump logcat from UncaughtExceptionHandler");
String filepath = getExternalFilesDir(null) + "/logcat.txt";
String cmd = "logcat -d -f "+filepath;
try {
Runtime.getRuntime().exec(cmd);
} catch (IOException ee) {
Log.d("Dump skipped");
}
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
File file = new File(logFolder, "LOG-"+ MyUtils.getTSsemicompact());
try {
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(errors.toString());
myOutWriter.close();
fOut.close();
} catch (Exception e1) {
e1.printStackTrace();
}
File toZip = getExternalFilesDir(null);
MyUtils.zipFolder(toZip);
//calling this because otherwise it would just stay stuck on the broken activity where the crash occurred
System.exit(0);//when debugging i can reach this line
}
});
}
public static Context getContext() {
return mContext;
}
}