How to start an activity from a thread class in android?

android, android-activity, multithreading

Solution

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

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

Problem

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

Original source