android – Is it safe to launch an activity from a non-ui thread?-ThrowExceptions

Exception or error:

Suppose my activity ui-thread spawns a separate thread at some point. Is it safe for that new thread to fire off an Intent for launching a new activity?

Thanks

How to solve:

I could be wrong, but I think startActivity() internally executes in the UI thread. So yes, it should be safe.

If you wanted to be 100% sure, invoke your startActivity() in your activity’s runOnUiThread() as a Runnable.

###

The first few lines of startActivityForResult() (used by all the startActivity() variants) suggests that it is ok:

public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
    if (mParent == null) {
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);

###

I have made an experiment:
– started activity from non ui thread and in onCreate() put a cycle from 1 to 100 where i were printing thread name Thread.currentThread()
– put the same cycle right after activity start in non ui thread

Output was simultaneously showing they names Thread[AsyncTask #1,5,main] and Thread[main,5,main]

Leave a Reply

Your email address will not be published. Required fields are marked *