Skip to content Skip to sidebar Skip to footer

Using A Thread To Run Code And Update Ui Android

How do I use a thread to run some code continuously whilst an Apps running, using the information it gives to periodically update the UI of the App. Specifically the thread would r

Solution 1:

This may help u...

//on create

Thread currentThread = new Thread(this); currentThread.start();

after on create

publicvoidrun() {
    try {
        Thread.sleep(4000);

        threadHandler.sendEmptyMessage(0);
    } catch (InterruptedException e) {
        //don't forget to deal with the Exception !!!!!
    }
} 

private Handler threadHandler = new Handler() {
    publicvoidhandleMessage(android.os.Message msg) {      


        Intent in = new Intent(getApplicationContext(),****.class);
        startActivity(in);

    }
};  

Solution 2:

This is a very common scenario and its far boyend the scope of a simple answer to your question.

Here are two usefull links:

http://developer.android.com/guide/components/processes-and-threads.htmlhttp://www.vogella.com/articles/AndroidBackgroundProcessing/article.html

And there are a lot more.

Here are two different approaches for you as starting point:

  1. Update gui from your thread, only needs syncronzation with the UI thread. Pass your Activity into your thread, it provides the method: runOnUiThread

  2. Define an interface to provide callbacks, let the calling ui class (activity) implement your interface and register it as listener to your thread. Then you can call the callback, when ever you want. Don't for to syncronize

Solution 3:

Try to use service(or IntentService - http://developer.android.com/guide/components/services.html) for background work and BroadcastReceiver to update the UI thread from the service.

Solution 4:

Use the AsyncTask class (instead of Runnable). It has a method called onProgressUpdate which can affect the UI (it's invoked in the UI thread).

Post a Comment for "Using A Thread To Run Code And Update Ui Android"