Android Thread/Runnable/Handler用法

public class MainActivity extends Activity implements OnClickListener {

//1.Runnable,实现Runnable类的方式
public class myRunnable implements Runnable{
 @Override
 public void run(){
   //写子线程中的操作
   init();
   }
}
//调用
Thread mRn=new Thread(new MyRunnable());
mRn.start();


//2.Thread,MyThread继承Thread类的方式
public class MyThread extends Thread{
  public void run(){
    init();
  }
}
//调用
MyThread mTh = new MyThread(); 
mTh.start();


3.Handler
private int count = 0;  
private Handler mHandler = new Handler();  
private Runnable mRunnable = new Runnable() {  
public void run() {  
       Log.e(TAG, Thread.currentThread().getName() + " " + count);  
       count++;   
       //每1秒执行一次  
       mHandler.postDelayed(mRunnable, 1000);  //给自己发送消息,自运行
     }  
  };   
   
//1.通过Handler启动线程  
mHandler.post(mRunnable);  //发送消息,启动线程运行    
//2.将线程销毁掉       
mHandler.removeCallbacks(mRunnable);
}

 

你可能感兴趣的:(Android,应用开发)