Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 646
Sando Avatar asked Jun 08 '11 05:06

Sando


People also ask

Is an activity a thread?

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).

How are threads executed in Android?

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).

Which action should be performed on 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.

Does service run on main thread Android?

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.


1 Answers

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

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

    Handler handler = new Handler(Looper.getMainLooper());
    
  2. 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);
        }
    });
    
like image 85
Alex Lockwood Avatar answered Sep 22 '22 07:09

Alex Lockwood