0

I have an alarm broadcast receiver where I want to check if my app is completely closed, which means app is neither running in foreground nor background.

Can anyone tells me how can I check this ?

Tushar H
  • 755
  • 11
  • 29
  • http://stackoverflow.com/questions/5593115/run-code-when-android-app-is-closed-sent-to-background This should hold all answers you need – Nico Feb 09 '17 at 08:03

2 Answers2

1

You can create a service and overwrite the onTaskRemoved() method

From the Documentation

the user has removed a task means swiping the app out from the task list. Stopping the Service from the phone's settings does not trigger Service.onTaskRemoved().

Code:

 public class AppStopped extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("Service", "Service Started");
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("Service", "Service Destroyed");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.e("Service", "END");
        Toast.makeText(getApplicationContext(), "App Stopped", Toast.LENGTH_SHORT).show();
        //Code here
        stopSelf();
    }
}

In Manifest:

<service android:name="com.example.AppStopped" 
     android:stopWithTask="false" />

Start the service in your activity like:

startService(new Intent(getBaseContext(), AppStopped.class));
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
-1

In your Application class:

public class MyApplication extends Application {    
    @Override
    public void onTerminate() {
        super.onTerminate();
        // your app is closed
    }
}
Thinsky
  • 4,226
  • 3
  • 13
  • 22