Reputation: 1748
I want to detect whether app is currently running (i.e, either on background or foreground) or not on click of notification. I have implemented Broadcast receiver where i want to check app state(running or not). I have already tried this check android application is in foreground or not? . But it is not working as excepted. Is there any other way to detect this?
Upvotes: 1
Views: 3443
Reputation: 430
You should take a look at a new component Handling Lifecycles. You can easily check the current state of activity, fragment, service and even process ProcessLifecycleOwner.
For example:
class CustomApplication extends Application {
private static Lifecycle lifecycle;
@Override
public void onCreate() {
super.onCreate();
lifecycle = ProcessLifecycleOwner.get().getLifecycle();
}
public static Lifecycle.State getCurrentState (){
return lifecycle.getCurrentState();
}
}
And then you can check a state:
if(customApplicationgetCurrentState().isAtLeast(Lifecycle.State.RESUMED)){
//do something
}
You can also add an observer to listen changes.
public class CustomApplication extends Application {
private static Lifecycle lifecycle;
public static Lifecycle.State getCurrentState() {
return lifecycle.getCurrentState();
}
@Override
public void onCreate() {
super.onCreate();
lifecycle = ProcessLifecycleOwner.get().getLifecycle();
lifecycle.addObserver(new SomeObserver());
}
public static class SomeObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreate() {
Log.d("Observer", ": onCreate");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onStop() {
Log.d("Observer", ": onStop");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
void onResume() {
Log.d("Observer", ": onResume");
}
}
}
Adding Components to your Project
Upvotes: 3
Reputation: 57
I can suggest you what I have done when the notification comes. override super method onNewIntent(Intent intent) in your activity that you have a pass in your pending intent, means desired activity that will be open when the user press on a notification. And here when your application is in the foreground then this method will be called, and if your application is killed then desired activity onCreate() will be called. And one more thing is to make your activity single top in Manifest.
In Manifest: <activity
android:name=".activities.TokenActivity"
android:label="@string/app_name_short"
android:launchMode="singleTop"/>
In Activity: @Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
loadCouponFragment(intent.getExtras());
}
Upvotes: 0
Reputation: 1629
This doesn't work this way - your application should start (via the same flow as usual) if it's no running.
You can pass some extras on the intent from your BroadcastReceiver into the app and it should be handled the way you need.
This is the only way to do it.
Upvotes: 0