Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference the current or main activity from another class

I often find myself needing to access methods that require referencing some activity. For example, to use getWindowManager, I need to access some Activity. But often my code for using these methods is in some other class that has no reference to an activity. Up until now, I've either stored a reference to the main activity or passed the context of some activity to the class. Is there some better way to do this?

like image 490
Johann Avatar asked Jun 27 '12 13:06

Johann


People also ask

How do you find the main activity?

1) Get your applicationContext by making your Android Application class a Singleton. 2) Get your ActivityManager class from the context. 3) Get a list of RunningTaskInfos using getRunningTasks() on the ActivityManager. 4) Get the first RunningTaskInfo element from the list which should be the most recent task launched.

How do you find the current activity in an application class?

This example demonstrates How to get current activity name in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do you call a method from one class to another in Android?

You should use the following code : Class2 cls2 = new Class2(); cls2. UpdateEmployee(); In case you don't want to create a new instance to call the method, you can decalre the method as static and then you can just call Class2.


1 Answers

If you already have a valid context, just use this: Activity activity = (Activity) context;

like image 170
Alessandro Muzzi Avatar answered Sep 22 '22 05:09

Alessandro Muzzi