- Reference
- http://blog.chinaunix.net/u/9577/showart_2323556.html
- http://developer.android.com/resources/articles/painless-threading.html
- Updating the UI from a Timer
http://developer.android.com/resources/articles/timed-ui-updates.html
- Import Classes
- Thread
- Runnable
- Timer & TimerTask
- Handler
Comments:
- By default, Handler is running in the thread where it is created. But you can make it to run in other thread by pass into Looper argument when to create Handler object.
- If you need to send & receive messages between 2 threads, create 2 Handler, each one is running in a respectively thread, and then you can use these 2 handler to send & receive messages.
- You can remove pending messages from message queue by invoking removeMessages().
Classes Related to Handler:
- HandlerThread
Run handler in addition thread. HandlerThread is sub-classes of Thread a HandlerThread contains a message loop; by default, Thread don't have a message loop with it.
- AsyncQueryHandler
For ContentResolver, execute query, delete, insert, and update option in addition thread.
- xxx
- Looper (and inner classes: MessageQueue)
- Use Looper in Thread
You can create instance of Handler in application main thread without any extra work, but if you need to do the operation out of main thread, you need to create Looper first. The followng code illustrats the usage of looper. i.e (Refer to HandlerThread.java)
class MyThread extends Thread
{
private Looper m_looper = null;
public Looper getLooper()
{
if (!isAlive()) return null;
synchronized(this)
{
while (!isAlive() && m_looper == null)
{
try
{
wait();
}
catch (InterruptedException e)
{
}
}
}
return m_looper;
}
public void run()
{
Looper.prepare();
synchronized(this)
{
m_looper = Looper.myLooper();
notifyAll();
}
Looper.loop(); //This is infinit loop, Handler running in the looper of this thread can not get any
message until this interface is invoked, even if
many messages have been sent to the Handler;
}
}
class MyHandler extends Handler()
{
public void handleMessage(Message msg)
{
// process incoming messages here
}
}
class OtherModule
{
private MyThread m_thread = null;
private MyHandler m_handler = null;
private void startThread()
{
if (m_thread == null)
{
m_thread = new MyThread();
m_thread.start();
m_handler = new MyHandler(m_thread.getLooper());
Message msg = m_handler.obtainMessage(xxx);
msg.sendToTarger();
}
}
private void stopThread()
{
if (m_thread != null)
{
Looper looper = m_thread.getLooper();
if (looper != null)
{
looper.quit();
//Or you can send message to Handler to quit the addition thread
}
m_thread = null;
}
}
}
============================================================
Simple way: Use HandlerThread
class OtherModule
{
private HandlerThread m_thread = null;
private MyHandler m_handler = null;
private void startThread()
{
if (m_thread == null)
{
m_thread = new HandlerThread();
m_thread.start();
m_handler = new MyHandler(m_thread.getLooper());
Message msg = m_handler.obtainMessage(xxx);
msg.sendToTarger();
}
}
private void stopThread()
{
if (m_thread != null)
{
Looper looper = m_thread.getLooper();
if (looper != null)
{
looper.quit();
//Or you can send message to Handler to quit the addition thread
}
m_thread = null;
}
}
}
- How to use thread in Android to update ui (Fresh View) elements
Android offers several ways to access the UI
thread from other threads:
(from: http://developer.android.com/resources/articles/painless-threading.html)
- Activity.runOnUiThread(Runnable)
- View.post(Runnable)
public void onClick(View v)
{
new Thread(new Runnable()
{
public void run()
{
final Bitmap b = loadImageFromNetwork();
mImageView.post(new Runnable()
{
public void run()
{
mImageView.setImageBitmap(b);
}
});
}
}).start();
}
- View.postDelayed(Runnable, long)
- Handler (main looper)
1st Way:
----------
public class MyActivity extends Activity
{
private TextView m_text;
private MyThread extends Thread
{
public void run()
{
int i = 0;
while (true)
{
try
{
new Handler(looper.getMainLooper).post(new Runnable()
{
m_text.setText((String)msg.obj); //Update ui
});
Thread.sleep(2000);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
}
public void onCreate(xxxx)
{
......
......
MyThread thread = new MyThread();
thread.start();
}
}
2nd Way:
----------
public class MyActivity extends Activity
{
private TextView m_text;
private MyThread extends Thread
{
private Handler m_handler;
public MyThread (Handler handler)
{
m_handler = handler;
}
public void run()
{
int i = 0;
while (true)
{
try
{
m_handler.post(new Runnable()
{
m_text.setText((String)msg.obj); //Update ui
});
Thread.sleep(2000);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
}
public void onCreate(xxxx)
{
......
......
MyThread thread = new MyThread(new MyHandler());
thread.start();
}
}
3rd Way:
----------
public class MyActivity extends Activity
{
private TextView m_text;
private MyThread extends Thread
{
private Handler m_handler;
public MyThread (Handler handler)
{
m_handler = handler;
}
public void run()
{
int i = 0;
while (true)
{
try
{
sendMessage(++i);
Thread.sleep(2000);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
public void sendMessage(String data)
{
Message msg = m_handler.obtainMessage();
msg.what = xxx;
msg.obj = data;
msg.sendToTarget();
}
}
private class MyHandler extends Handler
{
public void handleMessage(Message msg)
{
switch (msg.what)
{
case xxx:
m_text.setText((String)msg.obj); //Update ui
break;
case xxx:
break;
default:
break;
}
}
}
public void onCreate(xxxx)
{
......
......
MyThread thread = new MyThread(new MyHandler());
thread.start();
}
}
AsyncTask
This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
public void onClick(View v)
{
new DownloadImageTask().execute("http://example.com/image.png");
}
private class DownloadImageTask extends AsyncTask
{
protected Bitmap doInBackground(String... urls)
{
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Bitmap result)
{
mImageView.setImageBitmap(result);
}
}
- xxx
- Thread-Safe Topics
The entire view tree (Classes inherit from class View) is single threaded. You must always be on
the UI thread when calling any method on any view.
If you are doing work on other threads and want to update the state of a view
from that thread, you should use a Handler
. (From: http://developer.android.com/reference/android/view/View.html, search key words "Event Handling and Threading")
Methods of all other classes, if don't declare explicitly, are thread-safe, that means they can be invoked in non-UI thread, such as Context.
- How to process un-catched exception yourself
Register uncaught exception with interface 'public static void setDefaultUncaughtExceptionHandler', downlaod sample: http://blogimg.chinaunix.net/blog/upfile2/110209131545.zip
- xxx
阅读(1342) | 评论(0) | 转发(0) |