如何开始从Android的线程类的活动?线程、Android

2023-09-12 22:12:32 作者:此生╮只想爱你一个

我伸出一个线程类,并从该类我要开始一个活动。如何做到这一点?

I am extending a thread class and from that class I want to start an activity. How to do this?

推荐答案

您需要调用 startActivity()应用程序的主线程上。做到这一点的方法之一是通过执行以下操作:

You need to call startActivity() on the application's main thread. One way to do that is by doing the following:

初始化处理程序,并将其与应用程序的主线程关联起来。

Initialize a Handler and associate it with the application's main thread.

Handler handler = new Handler(Looper.getMainLooper());

裹在code将启动活动内部的匿名的Runnable 类,并通它的处理程序#后(可运行)方法。

Wrap the code that will start the Activity inside an anonymous Runnable class and pass it to the Handler#post(Runnable) method.

handler.post(new Runnable() {
    @Override
    public void run() {
        Intent intent = new Intent (MyActivity.this, NextActivity.class);
        startActivity(intent);
    }
});