简体   繁体   English

如何从非活动类调用MainActivity方法?

[英]How to call MainActivity method from non-Activity class?

I am having trouble on a runtime permission method in a non-activity class. 我在非活动类的运行时权限方法上遇到麻烦。 I want to call a public MainActivity method to a helper class. 我想将公共MainActivity方法调用到帮助程序类。

MainActivity.java method: MainActivity.java方法:

public void a() {
    //some method
}

Now my helper class: 现在我的助手课:

Class B {
    private Context mContext;
    public B(Context context) {
        this.mContext = context;
        //now I am calling Mainactivity Method
        MainActivity mainActivity = new MainActivity();
        mainActivity.a(); 
    }
}

Calling class B from CActivity: 从CActivity调用B类:

onCreate() {
    B b = new B(this);
}

But it gives me a runtime error. 但这给了我一个运行时错误。

UPDATE: 更新:

My method has a runtime permission method which isn't static. 我的方法有一个非静态的运行时权限方法。 Ex- requestPermissions(), onRequestPermissionsResult() . Ex- requestPermissions(), onRequestPermissionsResult()

Make that method as static so you can call without creating the class object 将该方法设置为静态,以便无需创建类对象即可调用

eg 例如

public static void testing() {}

now calling 现在打电话

MainActivity.testing();

I don't think its a good idea to construct activity directly. 我认为直接构建活动不是一个好主意。 If you want to signal the activity to do some task for your helper class (Class B), you better implement interfaces for listening or simply use EventBus library 如果您要发信号通知活动来为您的助手类(B类)执行某些任务,则最好实现用于侦听的接口 ,或者只是使用EventBus

If you really want to make your method work, rather than instantiating the Activity again in B class's constructor can you pass your activity as a parameter to B class? 如果您真的想使方法工作,而不是在B类的构造函数中再次实例化Activity,您可以将您的活动作为参数传递给B类吗? (I am not sure it would work) (我不确定它是否会起作用)

You can't just put B b = new B(this); 你不能只把B b = new B(this); because you're instantiating another class. 因为您要实例化另一个课程。

Instead, use getActivity() or getContext() . 而是使用getActivity() or getContext()

Remove class B. and call A activity's method directly in C activity. 删除类B。并在C活动中直接调用A活动的方法。

Extend your C activity with A activity like this: 使用以下A活动扩展C活动:

public class C extends A{
...
}

Then in C activity call A activity's method like below: 然后在C活动中调用A活动的方法,如下所示:

C.super.requestAppPermissions();

Hope it will help you. 希望对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM