我實現了與異步任務一起工作的代碼,它的工作原理非常完美,但是如果用戶退出應用程序,它會非常快速地被殺死,所以我決定嘗試使用服務,它完美地工作,但它會使應用程序凍結。解壓縮服務中的.zip文件會導致應用程序凍結,直至完成解壓縮爲止?
因此,這裏是我的解壓縮類:
public class Decompress {
private String _zipFile;
private String _location;
ZipEntry ze = null;
public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
while ((ze = zin.getNextEntry()) != null) {
//Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
這裏是我的服務電話進行解壓:
@Override
public void onStart(Intent intent, int startid)
{
try
{
zipFile = intent.getStringExtra("zipFile");
zipLocation = intent.getStringExtra("unzipLocation");
String fileS = intent.getStringExtra("file");
file = new File(fileS);
fin = new FileInputStream(zipFile);
zin = new ZipInputStream(fin);
while (zin.getNextEntry() != null) {
numFiles++;
}
}
catch (FileNotFoundException e)
{}
catch (IOException e)
{}
d = new Decompress(zipFile, zipLocation);
d.unzip();
}
現在,這裏就是我ussed與異步任務來調用它:
@Override
protected Void doInBackground(Void... params) {
d.unzip();
return null;
}
現在我的問題是,爲什麼與異步tsk我的應用程序不凍結,它會繼續unzipping讓我取消它與一個按鈕,但與服務,它使應用程序滯後?我甚至收到一條關於MyApp沒有迴應的消息,你想關閉它嗎?
編輯:我的服務呼叫的開始
@Override
protected Void doInBackground(Void... params) {
Intent intent = new Intent(DownloadFiles.this, MyService.class);
String unzipLocation = Environment.getExternalStorageDirectory().toString()+"/Android/data/";
String zipFile = Environment.getExternalStorageDirectory().toString()+"/Android/data/test.zip";
intent.putExtra("zipFile", zipFile);
intent.putExtra("unzipLocation", unzipLocation);
intent.putExtra("file", Environment.getExternalStorageDirectory().toString()+"/Android/data/");
startService(intent);
try {
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
while (zin.getNextEntry() != null) {
numFiles++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
我確實在同步任務中添加了服務調用,抱歉忘了添加它。將編輯我的OP。 –
OP編輯,服務電話 –
@RotaryHeart我更新了我的答案。長話短說,即使AsynTask啓動了它,服務仍在主線程中運行。 –