I'm very very new to android. Hopefully this is not a dumb question.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable()
{
public void run()
{
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
}).start();
}
Question: why does this work? is it normal that startActivity can be called from a secondary thread?
I thought that all UI related things had to be done in the UI thread.
If you call startActivity() for an Activity with default launch mode(i.e, you didn't mention any launch mode in either in manifest or in Intent) a new instance of the activity is created. For example, A launched B and again B launched A then Activity stack would be A - B - A.
So, with respect to time, setContentView alone is faster, since it doesn't start a new activity. Hence, your app will show the new screen faster... On the other hand, if you call startActivity, this activity is put on the stack, so you can go back by pressing the back button.
So is an activity is an independent thread? Yes and no. An Android app with one Activity will have a single process and single thread but if there are multiple app components they will normally all use the same thread (except for certain Android classes which use their own threads to do work).
Starting activities or services. To start an activity, use the method startActivity(intent) . This method is defined on the Context object which Activity extends. The following code demonstrates how you can start another activity via an intent.
startActivity
is not immediate. It schedules the start of the activity to run at the next available cycle on the main thread, so you can call it from anywhere. (That doesn't necessarily mean it's a good idea, though.)
You are not supposed to touch the view hierarchy anywhere except the main thread. That's a different issue.
startActivity
method can be called from anyActivity Context
A new instance of the thread has access to the Context
, which in turn has an Activity
. That is why your code is working.
Note that if this method is being called from outside of an
Activity Context
, then theIntent
must include theFLAG_ACTIVITY_NEW_TASK
launch flag. This is because, without being started from an existingActivity
, there is no existing task in which to place the new activity and thus it needs to be placed in its own separate task.
This method throws ActivityNotFoundException
if there was no Activity
found to run the given Intent.
For more info, read this developer manual
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With