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 mainActivity
. - I wish not. But it will startAlarmBroadcastReceiver
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
'sgetRunningTasks
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.