gpt4 book ai didi

android - 在android中解压缩文件时手机挂起

转载 作者:行者123 更新时间:2023-11-29 20:37:00 28 4
gpt4 key购买 nike

我正在尝试在 Android 手机中解压一个 .zip 文件。下面的代码工作正常。

public static void unzip(File zipFile, File targetDirectory) throws IOException {
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(new FileInputStream(zipFile)));
try {
ZipEntry ze;
int count;
byte[] buffer = new byte[8192];
while ((ze = zis.getNextEntry()) != null) {
File file = new File(targetDirectory, ze.getName());
File dir = ze.isDirectory() ? file : file.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs())
throw new FileNotFoundException("Failed to ensure directory: " +
dir.getAbsolutePath());
if (ze.isDirectory())
continue;
FileOutputStream fout = new FileOutputStream(file);
try {
while ((count = zis.read(buffer)) != -1)
fout.write(buffer, 0, count);
} finally {
fout.close();
}

/* if time should be restored as well
long time = ze.getTime();
if (time > 0)
file.setLastModified(time);
*/
}
} finally {
zis.close();
}

}

当我使用参数调用此方法时,它成功解压缩了文件,但问题是文件大小为 55MB,在调用此方法之前,应用程序运行良好,但当我调用此方法时,应用程序大约需要 8-13 秒需要解压缩应用程序卡住的文件,没有任何工作,但在成功解压缩文件后,应用程序再次运行良好所以请帮助我,以便应用程序在解压缩文件期间工作。我也尝试执行

中的方法
runOnUiThread(new Runnable() {

});

但没有获得成功。

最佳答案

如果应用程序卡住,通常是因为您在主/UI 线程上进行了太多计算(请注意 runOnUiThread() 正是这样做的)。为避免您必须在另一个线程或 AsyncTask 中调用您的方法.

一个快速而肮脏的修复方法是使用普通线程:

new Thread(new Runnable() {
public void run() {
unzip(zipFile, targetDirectory);
}
}).start();

或者使用 AsyncTask:

new AsyncTask<File, Void, Void>() {
protected Void doInBackground(File... files) {
unzip(files[0], files[1]);
return null;
}

protected void onPostExecute(Void result) {
// we're finished
}
}.execute(zipFile, targetDirectory);

关于android - 在android中解压缩文件时手机挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31372310/

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