0

Currently, I have a stock market app. When the stock market app "quit", it will start AlarmBroadcastReceiver, to monitor the stock market in background.

This code would looks like this.

// Code from main activity.
@Override
public void onPause() {
    super.onPause();
    ConnectivityChangeBroadcastReceiver.startAlarmBroadcastReceiver(this);

However, there's a tricky part here. It is extremely difficult to tell, when an app is "quit".

From end user perspective, "quit" really mean, when there is no Activity screen from the app package visible on screen.

onPause will be triggered in the following situations

  • Back button pressed. - Should start AlarmBroadcastReceiver
  • Home button pressed. - Should start AlarmBroadcastReceiver
  • Launch another Activity (Like settings preference activity) from main Activity. - I wish not. But it will start AlarmBroadcastReceiver with current code

It is difficult to differentiate Back button pressed / Home button pressed with Launch another Activity from main Activity.

Using isFinishing wouldn't work for my case, as it only return true during Back button pressed, not Home button pressed

Hence, I decide to install the following logic, at the early of AlarmBroadcastReceiver's onReceive

public class AlarmBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // If the current on screen activity, is *SAME* application package
        // as AlarmBroadcastReceiver. This mean our app is not "quit" yet.
        // We should return early without performing anything else.

However, I realize this is not an easy thing to do, as I can see from

How to get current foreground activity context in android?

  • ActivityManager's getRunningTasks is depreciated in Android 5.
  • Or, according to answer of gezdy, you need to have "hacky" code to update a global static variable, in every Activities in your app.

The suggested solution doesn't really look much elegant, and maintainable to me.

I was wondering, is there any better workaround, for my case? So that I can prevent AlarmBroadcastReceiver from running its logic code, when other Activity within same package is still visible on screen.

Community
  • 1
  • 1
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • apart from `onPause` there are other other "finishing" callbacks like `onStop` and `onDestroy`, try them – pskink Apr 19 '15 at 06:28

1 Answers1

1

Hope this help to some extent. This is what I found while googling around.

  1. You can register Activity Life Cycle with registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback) , but introduced in API Level 14.

  2. A blog written by Steve Liles - Is my Android app currently foreground or background using ActivityLifecycleCallbacks

Bharatesh
  • 8,943
  • 3
  • 38
  • 67