How to call a 'method' defined in another

2019-04-02 23:08发布

I know how to launch an activity on click of widget button using pending intent but I want to launch a particular method of that activity.

2条回答
一纸荒年 Trace。
2楼-- · 2019-04-02 23:09

If you need to call a method in another activity then you're following a wrong design. You should not put all of your code in the activities alone.

Why it's a bad choice -
Because you need an object of the class to call a method on it. And how would you get an object of the activity? Unless you are storing the object of one activity into another (That's a pretty messed up thing to do). Another problem in this approach is your other activity might have been destroyed already, so if you're relying on some of the UI element of another activity then you'll get no help at all. Making the activities static will open a huge can of worms for you.

So What's the option available -
There're a lot of options available for doing inter-activity method calls, but I rely on Singletons.They are classes which can have only one object which will be accessed statically, so you won't have to store an object of the class anywhere, since the class itself stores the object. It can go like the following -

public class AppManager{
  private static AppManager _instance = null;
  public static AppManager getInstance(){
    if(_instance == null)
      _instance= new AppManager();
    return _instance;
  }
  private AppManager(){} //Making the constructor private, so no 2 object can be created
  public void someMethod(){}
}

So in order to call someMethod() from any where in your project you'll just need to call

AppManager.getInstance().someMethod();

So do all your calculation in it. You can store the object of current activity in the Manager class or you can abstract out the functionality completely out of the Activity and can get better control over your code. And yes of course you can have more than one singleton classes. I normally have almost 6-7 Singleton managers in my project to handle different tasks.

查看更多
看我几分像从前
3楼-- · 2019-04-02 23:14

You need to use the same method in 2 different activites. So, best would to get another Class with that method and then call that method in both the activities.

public class A extends Activity 
{  

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

    }      

    B.method() 
}

public class B {

    public static void method()
    {

    }  

}

public class C extends Activity 
{  

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);

        B.method();

    }
}
查看更多
登录 后发表回答