简体   繁体   English

从扩展应用程序的另一个 class 的活动中调用方法

[英]Call method in an activity from another class that extends Application

Hi I am trying to call this method in MainActivity from another class called Startup that extends Application so that it could load each time the app starts:您好我正在尝试从另一个名为 Startup 的 class 在 MainActivity 中调用此方法,该方法扩展了 Application 以便每次应用程序启动时都可以加载:

Can someone show me how to do this?有人可以告诉我如何做到这一点吗? I have read lots of answers but I have not seen any questions that has a class that extends Application yet, I think that caused the issue.我已经阅读了很多答案,但我还没有看到任何具有扩展 Application 的 class 的问题,我认为这是导致问题的原因。 All answers that I have seen are about how to call a method from another class that extends Activity:/我看到的所有答案都是关于如何从另一个扩展 Activity 的 class 调用方法:/

this is the method in mainActivity:这是mainActivity中的方法:

 public void showPinLayout() {

        //if initialize in oncreate will cause nullpointer error
        indicatorDots = (IndicatorDots) findViewById(R.id.indicator_dotsMain);
        pinLockView = (PinLockView) findViewById(R.id.pinlockviewMain);
        pinLockView.attachIndicatorDots(indicatorDots);
...
}

this is the Startup class that extends Application and has been initialized in manifest:这是扩展应用程序并已在清单中初始化的启动 class:

<application
        android:name=".Startup" ...>
public class Startup extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        Toast.makeText(this, "Startup", Toast.LENGTH_SHORT).show();

        MainActivity mainActivity = new MainActivity();
        mainActivity.showPinLayout();
    }
}

I would suggest doing something like let the MainActivity start, and in onCreate of the MainActivity call the method in Startup class to initialize some method.我建议做一些事情,比如让MainActivity启动,并在MainActivityonCreate中调用Startup class 中的方法来初始化一些方法。 the reason is that you don't know at what time the activity will be initialized so wait for it then on Lifecycle Callback initialize some method if needed.原因是您不知道活动将在什么时间初始化,因此请等待它,然后在需要时在Lifecycle Callback 上初始化一些方法。

For ex.例如。

public class Startup extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        Toast.makeText(this, "Startup", Toast.LENGTH_SHORT).show();

       
    }

    public void initMain(Context context){
      ((MainActivity)context).showPinLayout();
    }

}

and in MainActivity do something like this.并在 MainActivity 做这样的事情。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //just before showing the UI, call the application class method to initialize some method if needed
    ((Startup)getApplicationContext()).initMain(this);
}

Since you cannot new an activity and you should not hold a static reference to an activity to call this method on (since it can lead to leaks), the proper way to access an activity method through app class is through BroadcastReceiver .由于您不能new活动,并且您不应该持有对活动的 static 引用来调用此方法(因为它可能导致泄漏),因此通过应用程序 class 访问活动方法的正确方法是通过BroadcastReceiver Here is a simple example:这是一个简单的例子:

MainActivity.java MainActivity.java

public class MainActivity extends AppCompatActivity {
    public static final String ACTION_SHOW_PIN_LAYOUT = "com.example.package.SHOW_PIN_LAYOUT";

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            showPinLayout();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate();
        ...
        registerReceiver(mReceiver, new IntentFilter(ACTION_SHOW_PIN_LAYOUT));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ...
        unregisterReceiver(mReceiver);
    }
}

Startup.java启动.java

public class Startup extends Application {

    ...

    public void callShowPinLayout() {
        sendBroadcast(new Intent(MainActivity.ACTION_SHOW_PIN_LAYOUT));
    }
}

Note that for this to work, MainActivity must be created first, so call callShowPinLayout in a resonable time when you have ensured of your activity creation.请注意,要使其正常工作,必须首先创建 MainActivity,因此请在确保创建活动的合理时间内调用callShowPinLayout

Also I'd suggest EventBus library which is created to ease out these kind of stuff.此外,我建议创建EventBus库以缓解此类问题。

Edit:编辑:

Since you intend to show a pin lock when user starts the app, you should only deal with activities.由于您打算在用户启动应用程序时显示密码锁,因此您应该只处理活动。 I would recommend implementing something like the following: Declaring your pin lock layout as an independent activity.我建议实施如下内容:将您的 pin 锁布局声明为独立活动。 Creating a startup activity (could be a splash screen) and marking it as the launcher activity in AndroidManifest.xml to decide whether to show the pin lock or main activity.创建一个启动活动(可能是启动屏幕)并将其标记为AndroidManifest.xml中的启动器活动,以决定是否显示引脚锁定或主要活动。

StartupActivity.java启动活动.java

public class StartupActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_startup);

        boolean shouldShowLockScreen = true;  // you can replace this with your own lock screen visibility algorithm
        if (shouldShowLockScreen) {
            // Open LockScreenActivity
            Intent intent = new Intent(this, LockScreenActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            // Open MainActivity
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        finish();
    }
}

AndroidManifest.java AndroidManifest.java

<application
    ...>
    <activity
        android:name=".StartupActivity"
        android:theme="@style/StartupTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
        ...
    </activity>
</application>

With this implementation whenever user enters the app with a cold start, the lock screen algorithm determines if he/she should enter MainActivity or not and if a hot start happens you can easily start your mighty StatupActivity if needed to in onResume() of your MainActivity .有了这个实现,每当用户以冷启动进入应用程序时,锁屏算法会确定他/她是否应该进入MainActivity ,如果发生热启动,您可以在MainActivityonResume()中轻松启动强大的StatupActivity .

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

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