简体   繁体   English

来自Android主要活动的呼叫功能

[英]Call function from main activity in Android

I have main activity (Activity started at beginning in singletop mode)... Than in another Activity I want to access function (below) in main activity 我有主要活动(活动从单顶模式开始)...比另一个活动,我想访问主要活动中的功能(如下)

public boolean checkConnections()
{

    if (isOnline() == false)
    {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Ni povezave!");
        alertDialog.setMessage("Pred uporabo je potrebno napravo povezati na internet!");
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {

            return;

        } }); 
        alertDialog.setButton2("Poizkusi ponovno", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {

                return;

            } }); 
        alertDialog.show();
        return false;
    }
    else
    {
        return true;
    }
}

Is this possible? 这可能吗? If it is I would like to ask how... 如果是的话,我想问一下...

You have to either inherit this main Activity or make this method static. 您必须继承此主要Activity或将此方法设为静态。 You can't properly invoke this method from another activity even if you'll have a reference to the main activity there because the view (dialog) needs a visible activity as a context. 即使您在其中引用了主活动,也无法从另一个活动中正确调用此方法,因为视图(对话框)需要将可见活动作为上下文。

No, the way you have described is not possible, as your main activity is invoked first, if your another activity from which you want to invoke that function is not initialized, then that function can not be called. 不,您描述的方法是不可能的,因为首先会调用您的主要活动,如果您要从中调用该功能的另一个活动未初始化,则无法调用该功能。 I suggest to put this function so that it can be reused. 我建议放置此函数,以便可以重复使用。 something like in singleton pattern class/utility class 类似单例模​​式类/实用程序类

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

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