Jaimit
Jaimit

Reputation: 61

Queue of runnables for run in other thread Android

that code will help me explain my problem:

public class TestHandlerActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    new  Thread(){
        public void run(){
            for (int i=0;i<20;i++){
                handler.post(run);
            }
        }
    }.start();
}

Handler handler=new Handler(){

};

Runnable run = new Runnable(){
    public void run(){
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.d("TAG", "Message processed");
    }
};
}

That way the new thread makes the petitions which are served by the handler in the main thread. What i need to do is exactly the opposite. The UI thread launches petitions wich are served sequentially by another thread (the order is important), and the UI thread don't need to be notified when each petition end. Some points are important for this: The petitions have 3 parameters (int, int, boolean), they make changes in the database and are generated by the interaction of the user with the UI, so they aren't launched simultaneously Thanks in advance

Upvotes: 2

Views: 1348

Answers (1)

hackbod
hackbod

Reputation: 91331

One option is to use this for making your thread: http://developer.android.com/reference/android/os/HandlerThread.html

This will create a thread with its own message queue and loop. You can create a Handler to run work on the thread like so:

HandlerThread handlerThread = new HandlerThread("My Handler");
handlerThread.start();
Handle myHandler = new Handler(handlerThread.getLooper());

This does require that all work done by thread be done so by sending messages and scheduling Runnables on it through Handlers.

Upvotes: 2

Related Questions