1

I have defined a public method in Activity class (lets say some_method()).Is it possible to call this method in Application class.

Durgesh
  • 291
  • 2
  • 19

1 Answers1

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