3

How to detect when my app close forcefully. I have try some way like service but it's not work proper. Service is close automatically even app in background. Is there any other way to detect app close without using service.

I have try below solution but not working proper. How to handle code when app is killed by swiping in android?

Basically i want to logout only if my app kill forcefully by user.

Raj Gohel
  • 524
  • 6
  • 11
  • Related: [How can I detect app kill on Android 8.0 Oreo API 26 and after](https://stackoverflow.com/q/54017641/295004) You might what to describe your use case and explain why you need to detect. – Morrison Chang Dec 04 '19 at 05:37
  • Generally, you can not detect force stop unless you put some flags in your activity or service. If that wasn't called in the next start, means it was force stopped. – Mahdi-Malv Dec 04 '19 at 05:59

2 Answers2

2

You can use Service to perform this task.

First create a Service class.

by adding extends Service // public class MyService extends Service

Then in service class create onDestroy

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy: called");
    //Your code 

}

Define service in AndroidManifest.xml

<service android:name=".MyService" android:enabled="true"
        android:exported="false" />

And it will work fine... I am already using it..

  • Service will work in all android version? Because i have check service not starting in pie. – Raj Gohel Dec 04 '19 at 06:47
  • 1
    And i already try service it's not work proper because some time service automatically close when my app in background. I don't want to stop service when my app in background. – Raj Gohel Dec 04 '19 at 06:49
  • No it will work in every version even in android Q i have tried and it's working. But After Api 26(Oreo) you can't run many queries in backend that consume the device battery or memory. As i said Service will work totally fine, In many cases. –  Dec 04 '19 at 06:52
  • @RajGohel if service automatically close when your app is in background. Then android OS is stopping your app. You have to find out why bcz apart Service boardcast receiver, JobScheduler they cannot perform that task. –  Dec 04 '19 at 06:56
  • Service is not reliable solution for this. @RajGohel Did you find any solution? – Aanal Shah Feb 21 '20 at 05:21
  • Can we relaunch the service once we detect it was killed from `onDestroy`? – IgorGanapolsky Apr 28 '20 at 03:32
-2

Handle the app in onDestroy() method of Activity/Fragment lifecycle. Inorder to logout, when app is closed forcefully, clear all the preferences in onDestroy() method.