当前位置: 动力学知识库 > 问答 > 编程问答 >

multithreading - 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 run some code that searches through a text file in order to find co-ordinates which would then be plotted over a PNG on the UI. This would update automatically say every second maybe every half second, and would clear the image then redraw the points.

How do i first of all set up the thread then second of all send information from the thread back to the UI and have it update?

Any example code would be great or any information you've come across that gives example code. I'm not trying to do it the best way at the moment, just trying to hack it together, so if you know easy and quick (but awful) ways of doing this don't feel afraid to share.

网友答案:

This may help u...

//on create

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

after on create

public void run() {
    try {
        Thread.sleep(4000);

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

private Handler threadHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {      


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

    }
};  
网友答案:

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.html http://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

网友答案:

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.

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: