You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity Android平台替代OnApplicationQuit实现应用终止时数据存储方案

Android Alternatives for Reliable System-Termination Data Saving

Great question—Android's app lifecycle is definitely trickier here compared to iOS, since OnApplicationQuit doesn't fire reliably when the OS terminates your running app process. Let's break down the most effective alternatives to get that one-time, system-termination-only data save:

1. Use onTrimMemory for Low-Memory Termination Signals

Android sends a memory-trim callback when it's running low on resources and preparing to kill background processes. This is the closest you'll get to an explicit "I'm going to terminate you" signal from the OS.

You can implement this in your custom Application class, and add a flag to ensure the save only runs once per app lifecycle:

public class MyApplication extends Application {
    private boolean hasSavedOnTermination = false;

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        // TRIM_MEMORY_COMPLETE means the app is in the background and the system is ready to kill it
        // TRIM_MEMORY_RUNNING_CRITICAL means the app is foreground but system is desperate for memory
        if ((level == ComponentCallbacks2.TRIM_MEMORY_COMPLETE || level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) && !hasSavedOnTermination) {
            saveYourCriticalData();
            hasSavedOnTermination = true;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        hasSavedOnTermination = false; // Reset flag when app starts fresh
    }

    private void saveYourCriticalData() {
        // Implement your data storage logic here (e.g., write to SharedPreferences, Room, etc.)
    }
}

Note: This isn't 100% guaranteed in all edge cases (like a sudden system crash), but it's the most reliable direct callback Android provides.

2. Combine Process Lifecycle Tracking with a "Background Save" Flag

If you want to cover cases where the app is sent to the background and later killed by the OS, you can use ProcessLifecycleOwner (from Android Architecture Components) to track when the app moves to the background, then save data once—resetting the flag when the app comes back to the foreground.

This ensures you only save once per background session, even if the system kills the app later:

public class MyApplication extends Application implements LifecycleObserver {
    private boolean hasSavedOnBackground = false;

    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onAppEnteredBackground() {
        if (!hasSavedOnBackground) {
            saveYourCriticalData();
            hasSavedOnBackground = true;
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onAppReturnedToForeground() {
        hasSavedOnBackground = false; // Reset flag when user comes back
    }

    private void saveYourCriticalData() {
        // Your data storage implementation
    }
}

Caveat: This will trigger when the user manually sends the app to the background (not just when the OS kills it). If you need to strictly only save on OS termination, pair this with the onTrimMemory check from the first method.

3. WorkManager as a Fallback

For a safety net, use WorkManager to schedule a delayed save task when the app goes to background. If the app returns to the foreground before the delay elapses, cancel the task. This ensures data gets saved even if the OS kills the app before the other callbacks fire.

public class MyApplication extends Application implements LifecycleObserver {
    private OneTimeWorkRequest saveWorkRequest;
    private WorkManager workManager;

    @Override
    public void onCreate() {
        super.onCreate();
        workManager = WorkManager.getInstance(this);
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onAppBackgrounded() {
        // Schedule save to run after 5 minutes (adjust delay as needed)
        saveWorkRequest = new OneTimeWorkRequest.Builder(SaveDataWorker.class)
                .setInitialDelay(5, TimeUnit.MINUTES)
                .build();
        workManager.enqueue(saveWorkRequest);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onAppForegrounded() {
        if (saveWorkRequest != null) {
            workManager.cancelWorkById(saveWorkRequest.getId());
        }
    }

    public static class SaveDataWorker extends Worker {
        public SaveDataWorker(@NonNull Context context, @NonNull WorkerParameters params) {
            super(context, params);
        }

        @NonNull
        @Override
        public Result doWork() {
            saveYourCriticalData();
            return Result.success();
        }

        private void saveYourCriticalData() {
            // Your data storage logic
        }
    }
}

Key Notes

Android doesn't have an exact equivalent to iOS's applicationWillTerminate because the OS can kill processes without warning to free up memory. The most robust approach is to combine onTrimMemory for immediate termination signals with WorkManager as a fallback to cover all edge cases.

内容的提问来源于stack exchange,提问作者Siddharth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:05:04