How to Execute Code When Application Is Closing

Run code when Android app is closed/sent to background


This answer only serves for one purpose, that is, running a code in onPause() for all activities. It doesn't let you run a code when your app is sent to background.

Original Answer

Make an Activity named YourBasicActivity and override its onPause() method and extend every Activity from YourBasicActivity

Android: Run code when application is permanently closed

you need to add a background service

public class BackgroundServices  extends Service

public void onCreate() {
Toast.makeText(this, "start", Toast.LENGTH_SHORT).show();

public int onStartCommand(Intent intent, int flags, int startId) {


public IBinder onBind(Intent intent) {

return null;

public void onDestroy() {


then in your activity. where you want to trigger this service


 startService(new Intent(getBaseContext(), BackgroundServices.class));

in your case it will be call on onDestory function of that activity

How to execute code when application is closing?


1.) use inMemory() configuration

RealmConfiguration config = new RealmConfiguration.Builder()

2.) Call realm.init() in Application.onCreate(), set the default configuration as usual, and afterwards, initialize/close Realm like this:

public class MyActivity extends AppCompatActivity {
private Realm realm;

protected void onCreate(Bundle savedInstanceState) {
realm = Realm.getDefaultInstance();

protected void onDestroy() {

Now when Realm is closed on all threads and you are quitting the app (or the app is killed), the Realm will be deleted.

How to execute code after application closure?

If your problem are the DLLs shared by the installer and main application, then you can do this: Before you run the installer, your main application can copy all the needed DLLs and the installer EXE from your main application folder to a temporary folder and run it from there. Your installer must then only wait until the main application gets closed and then replace all its files in the main folder. And once your update is finished, delete this temporary copy of the installer with its DLLs.

Note that if you want to overwrite files in Program Files folder, your installer will have to be run with elevated privileges. Google for "runas" command... you will need it when starting your installer with QProcess.

But there may be also other problems. If your first installation was with normal installer, it typically creates some entries in registry and also generates list of files for later uninstall. And if your new versions will contain different files than originally installed version, then your subsequent uninstall may malfunction or may leave some files existing on users' computers. And you certainly do not want this.

And yet another potential problem. You may have running several instances of your application. In that case quitting one instance will still leave the other instances running and hence their files will not be replacable by the installer - it will fail.

So as you can see, these are quire serious aspects to take into account.

How I do it in my software and I suggest you try it too? I prepare one installer file (.exe) with InnoSetup (freeware!). This can be used for first installation as well as for automatic updates. Then if I create a new version and put it on the server, the running main application detects it, downloads the new installer and runs this installer (of course it asks the user if it should proceed). The installer then asks for elevated privileges, asks to close the running application (it usually is closed automatically when starting the installer) and overwrites the existing installation. All this is standard functionality built in the installer created by InnoSetup. And correctly updates the uninstall instructions... It took me several days to set up everything to my needs but it works well. The only "drawback" is that it is not completely silent, it shows some dialogs. But this is no real issue for me. Maybe it is better for the users to see what is happening on their computer...

How can I run some code after application exiting

There isn't any way of having the program execute code once it is exited. I would say there are 3 sensible options of doing this.

  1. Have your program go into an "update state" where it basically closes all files/streams and everything else, then copies the files over. You shouldn't have any external files open so the files in use error won't be there.
  2. Have a seperate updating program. Basically once you try to update in your main program, this will launch the updater then close the main program once that has loaded. Once the updater has copied all the relevant files then the main program can be launched again.
  3. As commented by felix-b, there are a number of existing solutions which will handle the updating of your program. Such as or just google .NET application updater.

How to run code even if the app is closed

By default you would have to integrate your background service on a platform specific way.

But I found this package that handles the native integration mostly for you: flutter_background_service.

final service = FlutterBackgroundService();
await service.configure(
androidConfiguration: AndroidConfiguration(
// this will executed when app is in foreground or background in separated isolate
onStart: onStart,

// auto start service
autoStart: true,
isForegroundMode: true,
iosConfiguration: IosConfiguration(
// auto start service
autoStart: true,

// this will executed when app is in foreground in separated isolate
onForeground: onStart,

// you have to enable background fetch capability on xcode project
onBackground: onIosBackground,

Code snippet taken from the package example here.

How to add the package to your project:

  1. Open your pubspec.yaml file
  2. Add flutter_background_service: ^2.0.0 to your dependency section
  3. Run flutter pub get

Running a method when closing the program?

Add shutdown hook. See this javadoc.


public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
System.out.println("In shutdown hook");
}, "Shutdown-thread"));

Related Topics

Leave a reply