探寻Android的线程问题

2019-12-10 18:43:48于海丽

public class TestActivity extends Activity {
 
// ...
// all standard stuff
 
@Override
public void onCreate(Bundle savedInstanceState) {
 
   
// ...
   
// all standard stuff
 
   
// we're creating a new handler here
   
// and we're in the UI Thread (default)
   
// so this Handler is associated with the UI thread
  Handler mHandler = new Handler();
 
   
// I want to start doing something really long
   
// which means I should run the fella in another thread.
   
// I do that by sending a message - in the form of another runnable object
 
   
// But first, I'm going to create a Runnable object or a message for this
  Runnable mRunnableOnSeparateThread = new Runnable() {
    @Override
    public void run () {
 
       
// do some long operation
      longOperation();
 
       
// After mRunnableOnSeparateThread is done with it's job,
       
// I need to tell the user that i'm done
       
// which means I need to send a message back to the UI thread
 
       
// who do we know that's associated with the UI thread?
      mHandler.post(new Runnable(){
        @Override
        public void run(){
           
// do some UI related thing
           
// like update a progress bar or TextView
           
// ....
        }
      });
 
 
    }
  };
 
   
// Cool but I've not executed the mRunnableOnSeparateThread yet
   
// I've only defined the message to be sent
   
// When I execute it though, I want it to be in a different thread
   
// that was the whole point.
 
  new Thread(mRunnableOnSeparateThread).start();
}
 
}

如果根本就没有Handler对象,回调post方法会比较难办。

示例2:使用postDelayed方法

近期本站新介绍的特性中,我每次都要模拟EditText的自动完成功能,每次文字改变后都会触发一个API的调用,从服务器中检索数据。

我想减少APP调用API的次数,所以决定使用Handler的postDelayed方法来实现这个功能。

本例不针对平行处理,只是关于Handler给消息队列发送消息还有安排消息在未来的某一点执行等。

// the below code is inside a TextWatcher
// which implements the onTextChanged method
// I've simplified it to only highlight the parts we're
// interested in
 
private long lastChange = 0;
 
@Override
public void onTextChanged(final CharSequence chars,
             int start, int before, int count) {
 
     
// The handler is spawned from the UI thread
    new Handler().postDelayed(
 
       
// argument 1 for postDelated = message to be sent
      new Runnable() {
        @Override
        public void run() {
 
          if (noChangeInText_InTheLastFewSeconds()) {
            searchAndPopulateListView(chars.toString()); 
// logic
          }
        }
      },
 
       
// argument 2 for postDelated = delay before execution
      300);
 
    lastChange = System.currentTimeMillis();
}
 
 
private boolean noChangeInText_InTheLastFewSeconds() {
  return System.currentTimeMillis() - lastChange >= 300
}