前台服务每次都会被杀死

时间:2014-12-14 16:08:06

标签: android service process android-service

当我启动我的服务,在后台压缩很多文件时,它总是在大约8%和15-30秒之后被杀死。如何防止这种情况并让我的服务完成其任务?服务没有任何约束,这可能是问题吗?

//编辑: 我创建了一个前台服务,但它仍然被终止。

public class PackingService extends Service {
    String basePath = ""+ Environment.getExternalStorageDirectory();
    String source = basePath+"/data.zip";
    File dir = new File(basePath+"/data");


    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Zipping")
            .setContentText("...");

        startForeground(1337, nBuilder.build());

        try{
            ZipFile zipFile = new ZipFile(source);

            Log.d("ZIP", "Preparing files...");
            ArrayList filesToAdd = new ArrayList();
            addDirectory(dir, filesToAdd);

            ZipParameters parameters = new ZipParameters();
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);

            zipFile.setRunInThread(true);
            ProgressMonitor monitor = zipFile.getProgressMonitor();

            Log.d("ZIP", "Creating zip...");
            zipFile.createZipFile(filesToAdd, parameters);

            int percent = -1;
            while(monitor.getState() == ProgressMonitor.STATE_BUSY){
                if(percent != monitor.getPercentDone()) {
                    percent = monitor.getPercentDone();
                    Log.d("Progress", percent + "%");
                }
            }
        } catch (ZipException e) {
            e.printStackTrace();
        }

        stopForeground(true);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void addDirectory (File dir, ArrayList filesToAdd) {
        if (dir.exists()) {
            File[] files = dir.listFiles();
            for (int i = 0; i < files.length; ++i) {
                File file = files[i];
                if (file.isDirectory()) {
                    addDirectory(file, filesToAdd);
                } else {
                    filesToAdd.add(file);
                }
            }
        }
}

日志:

dalvikvm﹕ threadid=3: reacting to signal 3
dalvikvm﹕ Wrote stack traces to '/data/anr/traces.txt'

1 个答案:

答案 0 :(得分:0)

我通过不使用Service而是使用IntentService解决了这个问题。然后,我将整个压缩代码放入onHandleIntent的{​​{1}}方法中,然后在其前面调用IntentService。压缩完成后我打电话给startForeground,一切都很完美。