简体   繁体   English

如何开始一个新活动并在该活动中启动方法

[英]How to start a new activity and start a method in that activity

So I'm working with Java in android studio and I want to start a new class from a different class (I'm in ListenerServiceFromWear and want to start MainActivity ) and once Mainactivity is started I want to start a method ( startEmergencyMode(); ) in Mainactivity . 因此,我正在android studio中使用Java,我想从其他类中启动一个新类(我在ListenerServiceFromWear并想启动MainActivity ),一旦Mainactivity启动,我想启动一个方法( startEmergencyMode(); )在Mainactivity

How do I do this from ListenerServiceFromWear ? 如何从ListenerServiceFromWear做到这一点?

Start MainActivity with an intent and in the extra of the intent put some flag that will tell MainActivity to call startMergencyMode() 以一种意图启动MainActivity ,并在意图之外添加一些标志,该标志将告诉MainActivity调用startMergencyMode()

Intent intent = new Intent(this, Mainactivity.class);
intent.putExtra("isEmergency", true);
startActivity(intent);

And then in Mainactivity actually call startEmergencyMode() 然后在Mainactivity实际调用startEmergencyMode()

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // ...

    Intent intent = getIntent();
    boolean isEmergency = intent.getBooleanExtra("isEmergency", false);

    if(isEmergency){
        startEmergencyMode();
    }
}

I don't quite understand what you mean by "start" 我不太了解您所说的“开始”是什么意思

In java, you either: 在Java中,您可以:

  • Declare a static field or method 声明static字段或方法
  • Create an instance of an object and use its public fields and methods. 创建对象的实例,并使用其public字段和方法。

If you wish to just have one 'instance' of MainActivity , use a static method: 如果您只想拥有MainActivity一个“实例”,请使用静态方法:

public static void startEmergencyMode() {
    // Code here
}

Which you can call anywhere using MainActivity.startEmergencyMode() . 您可以使用MainActivity.startEmergencyMode()在任何地方调用它。 Keep in mind that this static method can only access static fields and other static methods. 请记住,此静态方法只能访问静态字段和其他静态方法。

If you wish to create an instance of MainActivity , simply create one and call the method: 如果要创建MainActivity的实例,只需创建一个实例并调用该方法:

public void startEmergencyMode() {
    // Code here
}


// Somewhere else
MainActivity activity = new MainActivity();
activity.startEmergencyMode();

If you don't understand the difference between a static and non static method or field, refer the answer on this thread: What does 'public static void' mean in Java? 如果您不了解静态方法和非静态方法或字段之间的区别,请参考此线程的答案: Java中的“ public static void”是什么意思?

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

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