/**
*
*/
package com.figo.study;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
* @author figo
*
*/
public class HandlerActivity extends Activity {
private Button btnHandler, btnClose;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler);
handler = new Handler();
btnHandler = (Button) findViewById(R.id.btnHandler);
btnClose = (Button) findViewById(R.id.btnClose);
// 开始执行定时任务
btnHandler.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 1秒后执行run
handler.postDelayed(run, 1000);
}
});
// 关闭定时任务
btnClose.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
handler.removeCallbacks(run);
}
});
}
// 其实是运行在UI主线程
Runnable run = new Runnable() {
@Override
public void run() {
// 这里new 一个AsyncTask或者Thread执行耗时任务,否则报ANR的bug
Toast.makeText(HandlerActivity.this, "test", Toast.LENGTH_SHORT)
.show();
// 每隔5秒后执行run方法
handler.postDelayed(this, 5000);
}
};
}
android开发步步为营之61:android定时任务之Handler.postDelayed
最新推荐文章于 2021-05-29 07:49:33 发布