Foreground service gets killed every time

2019-09-17 06:59发布

问题:

When I start my service that zips a lot of files in background it always gets killed after about 8% and 15-30 seconds. How can I prevent that and let my service finish its task? The service is not bound to anything, might this be the problem?

//EDIT: I created a foreground service out of it but it still gets terminated.

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);
                }
            }
        }
}

Logs:

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

回答1:

I solved the problem by not using Service but IntentService. I then put the whole zipping code into the onHandleIntent method of the IntentService and call startForeground before it. After zipping finishes I call stopForeground and everything works perfectly.