[英]starting activity from non main thread in Android
Please take a look at this code i found on android weekly here 请看看我每周在 android上发现的这段代码
there is one method in that article and its called from a non-UI thread. 该文章中有一种方法,它是通过非UI线程调用的。 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 ? 我的问题是如何从非uiThread启动startActivity? 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? 毕竟,这仅仅是OS启动一些新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 "? 也许您将其与“ Andoid UI工具包不是线程安全的。”这样的事实混淆了。因此,您一定不能从辅助线程中操作UI,而必须从UI线程对用户界面进行所有操作 ”吗?
I reviewed the startActivityForResult
and indeed you can startActivity
on non-UI thread. 我查看了startActivityForResult
,确实可以在非UI线程上使用startActivity
。 It seems when you call startActivity
it will run internally on main Thread. 似乎当您调用startActivity
,它将在内部主线程上运行。 Note that in the AOSP startActivity
calls startActivityForResult
which executes on main thread: 请注意,在AOSP中, startActivity
调用在主线程上执行的startActivityForResult
:
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);
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.