StartActivty in another topic

I am very new to android. Hope this is not a stupid 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 it work? Is it normal that startActivity can be called from a secondary thread?

I thought that all UI-related stuff should be done in the user interface thread.

+5
source share
2 answers

startActivity not immediate. It plans to start an action to start in the next available loop of the main thread, so you can call it from anywhere. (This does not necessarily mean that it is a good idea.)

You should not touch the view hierarchy anywhere except the main thread. This is another problem.

+3
source

startActivity method can be called from any Activity Context

A new thread instance has access to Context , which in turn has Activity . This is why your code works.

Note that if this method is called from outside the Activity Context , then the Intent must include the FLAG_ACTIVITY_NEW_TASK start flag. This is because, without starting from an existing Activity , there is no existing task to place a new activity and, therefore, it needs to be placed in a separate task.

This method throws an ActivityNotFoundException if no Activity found to trigger this intent.

Read this developer guide for more information.

+1
source

Source: https://habr.com/ru/post/1246355/


All Articles