Kill app when pushed to background


#1

Is there a way to kill an app on android if it is pushed to background?


#2

Sure thing, read the article on Application Lifecycle in the official documentation - https://docs.nativescript.org/core-concepts/application-lifecycle#use-application-events

You can register a handler for the suspended event, and call a helper function killProcess

var application = require("application");
application.on(application.suspendEvent, function (args) { 
   if (args.android) { 
      // For Android applications, args.android is an android activity class. 
      console.log("Activity: " + args.android); 
      killProcess(args.android);
   } else if (args.ios) { 
      // For iOS applications, args.ios is UIApplication. 
      console.log("UIApplication: " + args.ios); 
   }
});
function killProcess(context) {
// finish current activity and all below it first
try {
  context.finishAffinity();
} catch (e) {
 console.log("didn't terminate all activities")
}
// kill process
android.os.Process.killProcess(android.os.Process.myPid());
}

Make sure to leave a heart (like the response), or mark the response as the solution to your question if you found it helpful.


#3

Thanks man!!! worked like a charm.


#4

@Shlomo

It’s just one way to show appreciation to the forum contributors. I strongly advise users to ‘like’ posts they find helpful as ways to encourage others to respond more often!