Reputation: 135
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
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
Reputation: 317
I don't quite understand what you mean by "start"
In java, you either:
static
field or methodpublic
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