简体   繁体   中英

starting activity from non main thread in Android

Please take a look at this code i found on android weekly here

there is one method in that article and its called from a non-UI thread. The author spawned another child thread and started an activity:

private void restoreApp() {
    // Restart activity
    Intent i = new Intent(ctx, MyActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    ctx.startActivity(i);
}

My question is how is this possible to startActivity from a non-uiThread ? I thought this was discouraged or impossible. is it ok ?

Why you think "this was discouraged or impossible"? After all this is just a trigger for OS to start some new Activity? Maybe you confused it with the fact that " Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread "?

I reviewed the startActivityForResult and indeed you can startActivity on non-UI thread. It seems when you call startActivity it will run internally on main Thread. Note that in the AOSP startActivity calls startActivityForResult which executes on main thread:

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);
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM