Whenever my broadcast is executed I want to show alert to foreground activity.
-
from where you want to get context of Activity. Is this will be ur app activity or other application.– AAnkitJul 10, 2012 at 10:34
-
this is an app activity. I have done alert dialog coding on broadcastreceiver onreceive() function.– DeepaliJul 10, 2012 at 10:37
-
an app activity! is this your app?? and why do you want this, any reason, may there are alternative for the same– AAnkitJul 10, 2012 at 10:40
-
I want to show alert on my foreground activity.Is their any other way to show alert to foreground activity without context.– DeepaliJul 10, 2012 at 10:53
-
1in onreceive only u get COntext as a param, you can say context.getApplicationContext()– AAnkitJul 10, 2012 at 10:55
17 Answers
(Note: An official API was added in API 14: See this answer https://stackoverflow.com/a/29786451/119733)
DO NOT USE PREVIOUS (waqas716) answer.
You will have memory leak problem, because of the static reference to the activity. For more detail see the following link http://android-developers.blogspot.fr/2009/01/avoiding-memory-leaks.html
To avoid this, you should manage activities references. Add the name of the application in the manifest file:
<application
android:name=".MyApp"
....
</application>
Your application class :
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
}
private Activity mCurrentActivity = null;
public Activity getCurrentActivity(){
return mCurrentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
}
Create a new Activity :
public class MyBaseActivity extends Activity {
protected MyApp mMyApp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMyApp = (MyApp)this.getApplicationContext();
}
protected void onResume() {
super.onResume();
mMyApp.setCurrentActivity(this);
}
protected void onPause() {
clearReferences();
super.onPause();
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences(){
Activity currActivity = mMyApp.getCurrentActivity();
if (this.equals(currActivity))
mMyApp.setCurrentActivity(null);
}
}
So, now instead of extending Activity class for your activities, just extend MyBaseActivity. Now, you can get your current activity from application or Activity context like that :
Activity currentActivity = ((MyApp)context.getApplicationContext()).getCurrentActivity();
-
12You could just use WeakReference and achieve the same result with less code. May 26, 2013 at 15:55
-
5@Nacho I would never recomment to use
WeakReferences
in Android the GC collectes them faster then you think.– rekireJun 25, 2013 at 10:46 -
4@MaximKorobov Yes it is possible if you call finish() from onCreate(), if you use your activity just to launch another activity and stops this one. In this scenario it skips onPause() and onStoo(). See the bottom note of: developer.android.com/training/basics/activity-lifecycle/… Oct 30, 2013 at 16:45
-
3@rekire @NachoColoma Use of
WeakReference
is not advised for caching, this is not caching, that is themCurrentActivity
will only have a reference to it when it's alive so theWeakReference
will never be collected while theActivity
is on top. However what @NachoColoma suggest is wrong because theWeakReference
may still reference a non-resumed (not alive/not on top) activity if the variable is not cleared! Aug 13, 2014 at 13:52 -
14Starting from Android API level 14 it should be possible to use
Application .ActivityLifecycleCallbacks
, which would be more central and you wouldn't have to add any management code in all your activities. Also see developer.android.com/reference/android/app/…– FilouApr 14, 2015 at 12:45
I expand on the top of @gezdy's answer.
In every Activities, instead of having to "register" itself with Application
with manual coding, we can make use of the following API since level 14, to help us achieve similar purpose with less manual coding.
public void registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback)
In Application.ActivityLifecycleCallbacks
, you can get which Activity
is "attached" to or "detached" to this Application
.
However, this technique is only available since API level 14.
-
1What's up with all the other answers? Clearly this is designed API for this purpose. Thank you, Cheok Yan Cheng Jul 13, 2015 at 22:46
-
2@MichaelBushe - in 2012, when the other answers were written, depending on API level 14 was not something to rely on in every device, given that the API had only been recently released (Oct 2011). Oct 7, 2015 at 23:58
-
4Found an answer showing how to use this approach: stackoverflow.com/a/11082332/199364 The benefit is that nothing need be done to the activities themselves; the code is all in your custom callback class. You simply make a class that
implements Application.ActivityLifecycleCallbacks
, and add the methods to implement that. Then in that class' constructor (or onCreate or init or other method that runs when instance is becoming active/ready), putgetApplication().registerActivityLifecycleCallbacks(this);
as the last line. Oct 8, 2015 at 1:40 -
-
2great answer. the only downside is you still need to save the activity some place if you need to query your class for the current activity. so you still need to avoid memory leak and null the reference. Oct 6, 2016 at 11:09
Update 3: There is an official api added for this, please use ActivityLifecycleCallbacks instead.
-
3This answer should really get more up-votes, simple solution, but powerful when you have classes that need to manipulate activities, but aren't activities themselves. Oct 2, 2012 at 13:38
-
It's about just a static reference of your activity object. You can create it wherever you want :). It doesn't matter.– WaqasNov 24, 2012 at 11:23
-
This is btw equivalent to your previous answer.
Application
is only created once and never garbage collected exactly like a static variable.– zaplAug 8, 2013 at 1:14 -
1There'll be problems with hierarchic activities. When you return from a child activity to the parent one: (1) is called child's onPause; (2) parent's onResume; (3) child's onDestroy ==> the current activity will be null. You should do some check like @gezdy in his example in the method clearReferences.– ArtsFeb 26, 2014 at 21:56
-
4@waqas716 I'd suggest to simplify the condition in
clearReferences()
to(this.equals(currActivity))
. Jun 22, 2014 at 3:32
@lockwobr Thanks for update
This does not work 100% of the time in api version 16, if you read the code on github the function "currentActivityThread" was change in Kitkat, so I want to say version 19ish, kind of hard to match api version to releases in github.
Having access to the current Activity
is very handy. Wouldn’t it be nice to have a static getActivity
method returning the current Activity with no unnecessary questions?
The Activity
class is very useful. It gives access to the application’s UI thread, views, resources, and many more. Numerous methods require a Context
, but how to get the pointer? Here are some ways:
- Tracking the application’s state using overridden lifecycle methods. You have to store the current Activity in a static variable and you need access to the code of all Activities.
- Tracking the application’s state using Instrumentation. Declare Instrumentation in the manifest, implement it and use its methods to track Activity changes. Passing an Activity pointer to methods and classes used in your Activities. Injecting the pointer using one of the code injection libraries. All of these approaches are rather inconvenient; fortunately, there is a much easier way to get the current Activity.
- Seems like the system needs access to all Activities without the
issues mentioned above. So, most likely there is a way to get
Activities using only static calls. I spent a lot of time digging
through the Android sources on grepcode.com, and I found what I was
looking for. There is a class called
ActivityThread
. This class has access to all Activities and, what’s even better, has a static method for getting the currentActivityThread
. There is only one little problem – the Activity list has package access.
Easy to solve using reflection:
public static Activity getActivity() {
Class activityThreadClass = Class.forName("android.app.ActivityThread");
Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
activitiesField.setAccessible(true);
Map<Object, Object> activities = (Map<Object, Object>) activitiesField.get(activityThread);
if (activities == null)
return null;
for (Object activityRecord : activities.values()) {
Class activityRecordClass = activityRecord.getClass();
Field pausedField = activityRecordClass.getDeclaredField("paused");
pausedField.setAccessible(true);
if (!pausedField.getBoolean(activityRecord)) {
Field activityField = activityRecordClass.getDeclaredField("activity");
activityField.setAccessible(true);
Activity activity = (Activity) activityField.get(activityRecord);
return activity;
}
}
return null;
}
Such a method can be used anywhere in the app and it’s much more convenient than all of the mentioned approaches. Moreover, it seems like it’s not as unsafe as it looks. It doesn’t introduce any new potential leaks or null pointers.
The above code snippet lacks exception handling and naively assumes that the first running Activity is the one we’re looking for. You might want to add some additional checks.
-
2in Kitkat and above mActivities is not HashMap, but ArrayMap, so you need to change this line: HashMap activities = (HashMap) activitiesField.get(activityThread); to look like this: ArrayMap activities = (ArrayMap) activitiesField.get(activityThread); Oct 19, 2015 at 11:58
-
8@Palejandro for support both api levels (above 18 and below) it should use
Map
interface insteadHashMap
orArrayMap
. I've edited @AZ_ answer. Dec 23, 2015 at 8:35 -
2This does not work 100% of the time in api version 16, if you read the code on github the function "currentActivityThread" was change in Kitkat, so I want to say version 19ish, kind of hard to match api version to releases in github.– lockwobrOct 18, 2016 at 20:24
-
-
2Accessing internal APIs via reflection is not supported and may not work on all devices or in the future.– PeiAug 31, 2017 at 16:51
Knowing that ActivityManager manages Activity, so we can gain information from ActivityManager. We get the current foreground running Activity by
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
UPDATE 2018/10/03
getRunningTasks() is DEPRECATED. see the solutions below.
This method was deprecated in API level 21. As of Build.VERSION_CODES.LOLLIPOP, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak person information to the caller. For backwards compatibility, it will still return a small subset of its data: at least the caller's own tasks, and possibly some other tasks such as home that are known to not be sensitive.
-
17don't think so Martin, from SDK help of getRunningTasks "Note: this method is only intended for debugging and presenting task management user interfaces. This should never be used for core logic in an application"– ruhaldeJan 8, 2013 at 20:21
-
3Apparently this only supports a limited subset of running tasks in Android 5 / Lollipop.– SamJan 3, 2015 at 2:34
-
7The documentation for ActivityManager.getRunningTasks() says "This method was deprecated in API level 21".– markshepDec 15, 2016 at 15:26
I did the Following in Kotlin
- Create Application Class
Edit the Application Class as Follows
class FTApplication: MultiDexApplication() { override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) MultiDex.install(this) } init { instance = this } val mFTActivityLifecycleCallbacks = FTActivityLifecycleCallbacks() override fun onCreate() { super.onCreate() registerActivityLifecycleCallbacks(mFTActivityLifecycleCallbacks) } companion object { private var instance: FTApplication? = null fun currentActivity(): Activity? { return instance!!.mFTActivityLifecycleCallbacks.currentActivity } } }
Create the ActivityLifecycleCallbacks class
class FTActivityLifecycleCallbacks: Application.ActivityLifecycleCallbacks { var currentActivity: Activity? = null override fun onActivityPaused(activity: Activity?) { currentActivity = activity } override fun onActivityResumed(activity: Activity?) { currentActivity = activity } override fun onActivityStarted(activity: Activity?) { currentActivity = activity } override fun onActivityDestroyed(activity: Activity?) { } override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) { } override fun onActivityStopped(activity: Activity?) { } override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) { currentActivity = activity } }
you can now use it in any class by calling the following:
FTApplication.currentActivity()
-
2That's the only clean solution i found, btw you just need to run onActivityResumed, the other actions are useless as the resume is launched after the Activity is created. Just to be sure i would set currentActivity = null on onActivityStopped if currentActivity == activity– PlokkoOct 15, 2020 at 9:17
-
It works well, thank you. FYI: to activate the Callbacks, you have to add in AndroidManifest: <application android:name="your-package-code.FTApplication"– CaesarDec 13, 2021 at 9:58
getCurrentActivity() is also in ReactContextBaseJavaModule.
(Since the this question was initially asked, many Android app also has ReactNative component - hybrid app.)
class ReactContext in ReactNative has the whole set of logic to maintain mCurrentActivity which is returned in getCurrentActivity().
Note: I wish getCurrentActivity() is implemented in Android Application class.
-
in some cases this context from ReactContextBaseJavaModule is null, do you know why?– MoxorAug 2, 2018 at 19:05
For backwards compatibility:
ComponentName cn;
ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
cn = am.getAppTasks().get(0).getTaskInfo().topActivity;
} else {
//noinspection deprecation
cn = am.getRunningTasks(1).get(0).topActivity;
}
-
4Unless there's a way to get from ComponentName to the current instance of the Activity, this doesn't answer the question IMO.– naschMay 22, 2019 at 19:52
-
@nasch one can keep and get a
WeakReference
handle from anApplication
class - while theComponentName
is required to determine if the desiredActivity
is on top of the running tasks list. And if this does not fully answer the question, the accepted answer does not either. Sep 12, 2019 at 19:10 -
I agree, the accepted answer doesn't fully answer the question either.– naschSep 12, 2019 at 19:58
-
2
I could not find a solution that our team would be happy with so we rolled our own. We use ActivityLifecycleCallbacks
to keep track of current activity and then expose it through a service. More details here: https://stackoverflow.com/a/38650587/10793
Personally I did as "Cheok Yan Cheng" said, but I used a "List" to have a "Backstack" of all my activities.
If you want to check Which is the Current Activity you just need to get the last activity class in the list.
Create an application which extends "Application" and do this:
public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks,
EndSyncReceiver.IEndSyncCallback {
private List<Class> mActivitiesBackStack;
private EndSyncReceiver mReceiver;
private Merlin mMerlin;
private boolean isMerlinBound;
private boolean isReceiverRegistered;
@Override
public void onCreate() {
super.onCreate();
[....]
RealmHelper.initInstance();
initMyMerlin();
bindMerlin();
initEndSyncReceiver();
mActivitiesBackStack = new ArrayList<>();
}
/* START Override ActivityLifecycleCallbacks Methods */
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
mActivitiesBackStack.add(activity.getClass());
}
@Override
public void onActivityStarted(Activity activity) {
if(!isMerlinBound){
bindMerlin();
}
if(!isReceiverRegistered){
registerEndSyncReceiver();
}
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
if(!AppUtils.isAppOnForeground(this)){
if(isMerlinBound) {
unbindMerlin();
}
if(isReceiverRegistered){
unregisterReceiver(mReceiver);
}
if(RealmHelper.getInstance() != null){
RealmHelper.getInstance().close();
RealmHelper.getInstance().logRealmInstanceCount("AppInBackground");
RealmHelper.setMyInstance(null);
}
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
if(mActivitiesBackStack.contains(activity.getClass())){
mActivitiesBackStack.remove(activity.getClass());
}
}
/* END Override ActivityLifecycleCallbacks Methods */
/* START Override IEndSyncCallback Methods */
@Override
public void onEndSync(Intent intent) {
Constants.SyncType syncType = null;
if(intent.hasExtra(Constants.INTENT_DATA_SYNC_TYPE)){
syncType = (Constants.SyncType) intent.getSerializableExtra(Constants.INTENT_DATA_SYNC_TYPE);
}
if(syncType != null){
checkSyncType(syncType);
}
}
/* END IEndSyncCallback Methods */
private void checkSyncType(Constants.SyncType){
[...]
if( mActivitiesBackStack.contains(ActivityClass.class) ){
doOperation() }
}
}
In my case I used "Application.ActivityLifecycleCallbacks" to:
Bind/Unbind Merlin Instance (used to get event when the app lose or get connection, for example when you close mobile data or when you open it). It is useful after the "OnConnectivityChanged" intent action was disabled. For more info about MERLIN see: MERLIN INFO LINK
Close my last Realm Instance when the application is closed; I will init it inside a BaseActivity wich is extended from all others activities and which has a private RealmHelper Instance. For more info about REALM see: REALM INFO LINK For instance I have a static "RealmHelper" instance inside my "RealmHelper" class which is instantiated inside my application "onCreate". I have a synchronization service in which I create I new "RealmHelper" because Realm is "Thread-Linked" and a Realm Instance can't work inside a different Thread. So in order to follow Realm Documentation "You Need To Close All Opened Realm Instances to avoid System Resources Leaks", to accomplish this thing I used the "Application.ActivityLifecycleCallbacks" as you can see up.
Finally I have a receiver wich is triggered when I finish to synchronize my application, then when the sync end it will call the "IEndSyncCallback" "onEndSync" method in which I look if I have a specific Activity Class inside my ActivitiesBackStack List because I need to update the data on the view if the sync updated them and I could need to do others operations after the app sync.
That's all, hope this is helpful. See u :)
by using this part of code you detect when your app goes background/foreground and you access the current activity name and context.
My answer is based on this article : Android: How to detect when App goes background/foreground
First, create a class that extends the android.app.Application
and implements the ActivityLifecycleCallbacks
interface. In the Application.onCreate()
, register the callback.
public class App extends Application implements ActivityLifecycleCallbacks
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
}
Register the “App” class in the Manifest as below,
<application
android:name=".App"
This is how the ActivityLifecycleCallbacks interface looks like,
public interface ActivityLifecycleCallbacks {
void onActivityCreated(Activity activity, Bundle savedInstanceState);
void onActivityStarted(Activity activity);
void onActivityResumed(Activity activity);
void onActivityPaused(Activity activity);
void onActivityStopped(Activity activity);
void onActivitySaveInstanceState(Activity activity, Bundle outState);
void onActivityDestroyed(Activity activity);
}
So, when any of your Activity(Activities you created or included by your Libraries) goes through any of the above mentioned lifecycle methods, these callbacks will be called. There will be at least one Activity in the started state when the app is in the foreground and there will be no Activity in the started state when the app is in the background. Declare 2 variables as below in the “App” class.
private int activityReferences = 0;
private boolean isActivityChangingConfigurations = false;
activityReferences will keep the count of number of Activities in the started state. isActivityChangingConfigurations is a flag to indicate if the current Activity is going through configuration change like orientation switch. Using the following code you can detect if the App comes foreground.
@Override
public void onActivityStarted(Activity activity) {
if (++activityReferences == 1 && !isActivityChangingConfigurations) {
// App enters foreground
}
}
You can access context in this method like this :
activity.getBaseContext()
This is how to detect if the App goes background.
Override
public void onActivityStopped(Activity activity) {
isActivityChangingConfigurations = activity.isChangingConfigurations();
if (--activityReferences == 0 && !isActivityChangingConfigurations) {
// App enters background
}
}
Now you can access the current foreground activity name and context.
You can use this Class for flexible lifecycle handling
Usage:
//Initialization
val lifeCycleHandler = ActivityLifeCycleHandler<Activity>()
//Detect only a specific type of activities
val lifeCycleHandler = ActivityLifeCycleHandler<MainActivity>()
//Get current activity
val instance = lifeCycleHandler.currentReference
//Get current activity state
val state = lifeCycleHandler.currentState
//Use listeners
lifeCycleHandler.addStateChangeListener { newState ->
//TODO: handle new state
}
lifeCycleHandler.addSpecificStateChangeListener(ActivityLifeCycleHandler.ActivityState.STARTED) {
//TODO: handle new state
}
//Removable listeners
val listener = { newState: Int ->
}
lifeCycleHandler.addStateChangeListener(listener)
lifeCycleHandler.removeStateChageListener(listener)
//Start listening
App.app.registerActivityLifecycleCallbacks(lifeCycleHandler)
//Stop listening
lifeCycleHandler.releaseListeners()
App.app.unregisterActivityLifecycleCallbacks(lifeCycleHandler)
Use the is
operator or its negated form !is
to perform a runtime check that identifies whether an object conforms to a given type:
if (this !is OneActivity) {
// do something
} else if (this !is TwoActivity) {
// do something 2
}
The answer by waqas716 is good. I created a workaround for a specific case demanding less code and maintenance.
I found a specific work around by having a static method fetch a view from the activity I suspect to be in the foreground. You can iterate through all activities and check if you wish or get the activity name from martin's answer
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
I then check if the view is not null and get the context via getContext().
View v = SuspectedActivity.get_view();
if(v != null)
{
// an example for using this context for something not
// permissible in global application context.
v.getContext().startActivity(new Intent("rubberduck.com.activities.SomeOtherActivity"));
}
-
I am looking for similar issue here stackoverflow.com/questions/22788289/… how do we get "SuspectedActivity" ? Is this native API?– StellaApr 2, 2014 at 17:18
-
2BUT from docs for
getRunningTasks
:"Note: this method is only intended for debugging and presenting task management user interfaces. This should never be used for core logic in an application, ..."
in developer.android.com/reference/android/app/… Oct 7, 2015 at 22:59 -
3The documentation for ActivityManager.getRunningTasks() now says "This method was deprecated in API level 21".– markshepDec 15, 2016 at 15:38
I don't like any of the other answers. The ActivityManager is not meant to be used for getting the current activity. Super classing and depending on onDestroy is also fragile and not the best design.
Honestly, the best I have came up with so far is just maintaining an enum in my Application, which gets set when an activity is created.
Another recommendation might be to just shy away from using multiple activities if possible. This can be done either with using fragments, or in my preference custom views.
-
1an enum? How does that help locate the current foreground activity instance? Oct 7, 2015 at 23:02
-
"Super classing and depending on onDestroy is also fragile" How is that fragile? Oct 8, 2015 at 0:58
A rather simple solution is to create a singleton manager class, in which you can store a reference to one or more Activities, or anything else you want access to throughout the app.
Call UberManager.getInstance().setMainActivity( activity );
in the main activity's onCreate.
Call UberManager.getInstance().getMainActivity();
anywhere in your app to retrieve it. (I am using this to be able to use Toast from a non UI thread.)
Make sure you add a call to UberManager.getInstance().cleanup();
when your app is being destroyed.
import android.app.Activity;
public class UberManager
{
private static UberManager instance = new UberManager();
private Activity mainActivity = null;
private UberManager()
{
}
public static UberManager getInstance()
{
return instance;
}
public void setMainActivity( Activity mainActivity )
{
this.mainActivity = mainActivity;
}
public Activity getMainActivity()
{
return mainActivity;
}
public void cleanup()
{
mainActivity = null;
}
}
-
This is intrusive and requires changes in all the activities. The answer by AZ_ is much better as it's totally localised and standalone without requiring other changes in the codebase.– markshepDec 15, 2016 at 15:42
I'm like 3 years late but I'll answer it anyway in case someone finds this like I did.
I solved this by simply using this:
if (getIntent().toString().contains("MainActivity")) {
// Do stuff if the current activity is MainActivity
}
Note that "getIntent().toString()" includes a bunch of other text such as your package name and any intent filters for your activity. Technically we're checking the current intent, not activity, but the result is the same. Just use e.g. Log.d("test", getIntent().toString()); if you want to see all the text. This solution is a bit hacky but it's much cleaner in your code and the functionality is the same.