当前位置:操作系统 > 安卓/Android >>

关于Thread和Handler的使用(一)

public class TestHandlerAty extends Activity {

 

private android.os.Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btn_start = (Button) findViewById(R.id.btn_start);
        Button btn_stop = (Button) findViewById(R.id.btn_stop);
        btn_start.setOnClickListener(new View.OnClickListener() {

 

@Override

public void onClick(View v) {

mHandler.post(mThread); // 开始调用线程,执行run()方法,输出run...

}

});
        btn_stop.setOnClickListener(new View.OnClickListener() {

 

@Override

public void onClick(View v) {

mHandler.removeCallbacks(mThread); // 移除mThread,不再输出run...

}

});
    }

    private Thread mThread = new Thread(new Runnable(){


@Override

public void run() {

Log.d("test", "run...");

mHandler.postDelayed(mThread, 3000);// 3秒钟之后执行mThread,即run()方法,输出run...

}

    });

}

作者“维王的博客”
 

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,