I have defined a public method in Activity class (lets say some_method()).Is it possible to call this method in Application class.
Asked
Active
Viewed 2,065 times
1
-
I thing you need to create a new class and add this method in your class use it in activity and Application class. – Yaseen Ahmad Aug 24 '16 at 07:20
-
@Durgesh - Did you try? What happened? – Bö macht Blau Aug 24 '16 at 07:27
-
I am editing in already created project.So I can't change Activity class. – Durgesh Aug 24 '16 at 07:29
-
Because of this I am looking for the asked option if available. – Durgesh Aug 24 '16 at 07:30
1 Answers
3
you can use a singleton activity like this:
public class YourActivity extends AppCompatActivity {
public static YourActivity instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
instance=this;
//your code
}
//your method
public void yourMethod() {
}
@Override
protected void onDestroy() {
super.onDestroy();
instance=null;
}
}
then in your application method you can call the method of your activity like this:
if (YourActivity.instance != null) {
YourActivity.instance.yourMethod();
}

Bronx
- 4,480
- 4
- 34
- 44
-
I know this feels quick and easy, but you should avoid making static references to activities at all costs. It's an anti-pattern because it's really easy to miss nullifying it at the right times and end up with a memory leak. Using BroadcastReceivers or Intents (they can work on already running components) is the recommended way to call methods between activity/app/service boundaries – Cody Jan 29 '20 at 18:01