-2

My query is, i want to cancel services using alarm manager when application going to destroy/closed.

if i am in activity A by clicking on button started activity B suddenly user is going to press home button. ---- if application is running in background then don't cancel service. but when he going to remove from recent list of application at that time cancel service.

Service/Alarm manager will work even when user has sent application in background by pressing home screen.

No of way application can closed.
1) By clicking back button (multiple times if stack have multiple activities).
2) By pressing home button and then remove from recent list.

i am facing issue with (2)second option. in that when user press home button at that time service or alarm manager should be work. But when user will be going to remove application from recent list at that time i want to cancel service/alarm manager.

Is there any Listners/Methods through which we can identify?

Bhavesh Jethani
  • 3,891
  • 4
  • 24
  • 42

2 Answers2

1

Whenever My service is going to execute at that i am now checking isAppRunning() if it returns true then execute Service Otherwise cancel the service, simple:)

public boolean isAppRunning(Context context)
        {
            boolean appFound = false;
            final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            final List<RunningTaskInfo> recentTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

            for (int i = 0; i < recentTasks.size(); i++)
            {
                if (recentTasks.get(i).baseActivity.getPackageName().equals("mypackagename"))
                {
                    appFound = true;
                    break;
                }
            }
            return appFound;
        }


Add Permission

<uses-permission android:name="android.permission.GET_TASKS" />

So whenever it is remove from recent list. i will know by this method.

Bhavesh Jethani
  • 3,891
  • 4
  • 24
  • 42
-1

Add onDestroy() in your class

@Override
     protected void onDestroy() {
         super.onDestroy();
         //do your code here
     }
Ramki Anba
  • 754
  • 1
  • 10
  • 21