How to get current foreground activity context in android?
How to get current foreground activity context in android?
Whenever my broadcast is executed I want to show alert to foreground activity.
Answer by waqas716 for How to get current foreground activity context in android?
[[UPDATE]]
As pointed by @gezdy, and I'm grateful for that. set reference to null too for current activity, instead of updating on just every onResume set it to null on every Activity's onDestroy to avoid memory leak problem.
A while ago I needed the same functionality and here is the method how I achieved this. In your every activity override these life cycle methods.
@Override protected void onResume() { super.onResume(); appConstantsObj.setCurrentActivity(this); } @Override protected void onPause() { clearReferences(); super.onPause(); } @Override protected void onDestroy() { clearReferences(); super.onDestroy(); } private void clearReferences(){ Activity currActivity = appConstantsObj.getCurrentActivity(); if (this.equals(currActivity)) appConstantsObj.setCurrentActivity(null); }
Now in your broadcast class you can access current activity to show alert on it.
Answer by KAlO2 for How to get current foreground activity context in android?
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;
Answer by Rubber Duck for How to get current foreground activity context in android?
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")); }
Answer by gezdy for How to get current foreground activity context in android?
(Note: An official API was added in API 14: See this answer http://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:
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();
Answer by AZ_ for How to get current foreground activity context in android?
@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
ActivityThread
. This class has access to all Activities and, what?s even better, has a static method for getting the current ActivityThread
. 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
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.
Answer by Cheok Yan Cheng for How to get current foreground activity context in android?
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.
Answer by stevebot for How to get current foreground activity context in android?
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.
Answer by Simon Hyll for How to get current foreground activity context in android?
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.
Answer by MukRaker for How to get current foreground activity context in android?
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; } }
Answer by Muxa for How to get current foreground activity context in android?
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: http://stackoverflow.com/a/38650587/10793
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72
0 comments:
Post a Comment