I am extending a thread class and from that class I want to start an activity. How to do this?
So is an activity is an independent thread? Yes and no. An Android app with one Activity will have a single process and single thread but if there are multiple app components they will normally all use the same thread (except for certain Android classes which use their own threads to do work).
When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. By default, all components of the same application run in the same process and thread (called the "main" thread).
The main thread is responsible for dispatching events to the appropriate user interface widgets as well as communicating with components from the Android UI toolkit. To keep your application responsive, it is essential to avoid using the main thread to perform any operation that may end up keeping it blocked.
Caution: A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise. You should run any blocking operations on a separate thread within the service to avoid Application Not Responding (ANR) errors.
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With