探寻Android的线程问题

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

public class ListProgressDemo extends ListActivity { 
 
 @Override
 public void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.listprogress); 
 
  ((Button) findViewById(R.id.load_Handler)).setOnClickListener(new View.OnClickListener(){ 
 
   @Override
   public void onClick(View view) { 
    data = null; 
    data = new ArrayList<string>(); 
 
    adapter = null; 
 
    showDialog(PROGRESS_DIALOG); 
    new ProgressThread(handler, data).start(); 
   } 
  }); 
 } 
 
 @Override
 protected Dialog onCreateDialog(int id) { 
  switch(id) { 
  case PROGRESS_DIALOG: 
     return ProgressDialog.show(this, "", 
     "Loading. Please wait...", true); 
 
  default: return null; 
  } 
 } 
 
 private class ProgressThread extends Thread { 
 
  private Handler handler; 
  private ArrayList<string> data; 
 
  public ProgressThread(Handler handler, ArrayList<string> data) { 
   this.handler = handler; 
   this.data = data; 
  } 
 
  @Override
  public void run() { 
   for (int i=0; i<8; i++) { 
    data.add("ListItem"); //后台数据处理
    try { 
     Thread.sleep(100); 
    }catch(InterruptedException e) { 
      
     Message msg = handler.obtainMessage(); 
     Bundle b = new Bundle(); 
     b.putInt("state", STATE_ERROR); 
     msg.setData(b); 
     handler.sendMessage(msg); 
      
    } 
   } 
   Message msg = handler.obtainMessage(); 
   Bundle b = new Bundle(); 
   b.putInt("state", STATE_FINISH); 
   msg.setData(b); 
   handler.sendMessage(msg); 
  } 
   
 } 
 
 // 此处甚至可以不需要设置Looper,因为Handler默认就使用当前线程的Looper
 private final Handler handler = new Handler(Looper.getMainLooper()) {
 
  public void handleMessage(Message msg) { // 处理Message,更新ListView
   int state = msg.getData().getInt("state"); 
   switch(state){ 
    case STATE_FINISH: 
     dismissDialog(PROGRESS_DIALOG); 
     Toast.makeText(getApplicationContext(), 
       "加载完成!", 
       Toast.LENGTH_LONG) 
       .show(); 
 
     adapter = new ArrayAdapter<string>(getApplicationContext(), 
       android.R.layout.simple_list_item_1, 
       data ); 
        
     setListAdapter(adapter); 
 
     break; 
 
    case STATE_ERROR: 
     dismissDialog(PROGRESS_DIALOG); 
     Toast.makeText(getApplicationContext(), 
       "处理过程发生错误!", 
       Toast.LENGTH_LONG) 
      .show(); 
 
     adapter = new ArrayAdapter<string>(getApplicationContext(), 
       android.R.layout.simple_list_item_1, 
       data ); 
        
      setListAdapter(adapter); 
 
      break; 
 
    default: 
 
   } 
  } 
 }; 
 
 
 private ArrayAdapter<string> adapter; 
 private ArrayList<string> data; 
 
 private static final int PROGRESS_DIALOG = 1; 
 private static final int STATE_FINISH = 1; 
 private static final int STATE_ERROR = -1; 
}