Android Thread 与 Handler


package com.ltc.thread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ActivityMain extends Activity {
    
	private TextView textView = null;
	private Button btn = null;
	
	private Thread thread = null;
	private Thread thread2 = null;
	
	public Handler handler;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        findVeiws();
        setListeners();
    }
    
    private void findVeiws(){
    	textView = (TextView)findViewById(R.id.mytextview);
        btn = (Button)findViewById(R.id.actmain_btn_threadrun);
    }
    
    private void setListeners(){
        btn.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				testThread();
			}
		});   	
    }
    
    private void testThread(){
    	
        thread = new Thread(new Runnable() {
        				
			@Override
			public void run() {
				Thread.currentThread();
				int i = 0;
				while(i++ < 10){
					
					Log.e("LOG", "-------------"+i);
					
					Message msg = handler.obtainMessage();
                    msg.arg1 = i;
                    msg.sendToTarget();
					
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
        thread.start();
        
        handler = new Handler(){
        	@Override
        	public void handleMessage(Message msg) {
        		// TODO Auto-generated method stub
        		
        		textView.setText(""+msg.arg1);
        		
        		if(msg.arg1 == 1){
        			thread2 = new Thread(new Runnable() {
						
						@Override
						public void run() {
							Thread.currentThread();
							
							int j = 0;
							while(j++ < 10){
								Log.e("aaaaaaaaaaaaa", "j----"+j);
								
								try {
									Thread.sleep(250);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
					});
        			thread2.start();
        		}
        		
        		if(msg.arg1 == 10){
        			Log.e("bbbbbbbbbbbbbb", "bbbbbbbbbb");
//        			thread2.stop();
        		}
        		
        		super.handleMessage(msg);
        	}
        };
    }
}


你可能感兴趣的:(Android Thread 与 Handler)