hxwtch
hxwtch

Reputation: 135

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.

How do I do this from ListenerServiceFromWear?

Upvotes: 0

Views: 133

Answers (2)

litelite
litelite

Reputation: 2848

Start MainActivity with an intent and in the extra of the intent put some flag that will tell MainActivity to call startMergencyMode()

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

And then in Mainactivity actually call startEmergencyMode()

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

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

    if(isEmergency){
        startEmergencyMode();
    }
}

Upvotes: 1

086
086

Reputation: 317

I don't quite understand what you mean by "start"

In java, you either:

  • Declare a static field or method
  • Create an instance of an object and use its public fields and methods.

If you wish to just have one 'instance' of MainActivity, use a static method:

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

Which you can call anywhere using 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:

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?

Upvotes: 0

Related Questions