val TAG: String = "MyActivity"
class MainActivity : AppCompatActivity() {
private var btn1: Button? = null
private var btn2: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn1 = findViewById(R.id.btn1)
btn2 = findViewById(R.id.btn2)
// if (!Settings.canDrawOverlays(this)) {
// val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
// intent.data = Uri.parse("package:$packageName")
// startActivityForResult(intent, 0)
// }
}
@RequiresApi(Build.VERSION_CODES.P)
fun btn1(view: View?) {
/*
// demo1 使用handler处理延时任务
Log.e(TAG, "demo1: handler outer")
// 创建Handler对象
val handler = Handler(Looper.myLooper()!!)
// 发送延时消息
val token = "AAA"
handler.postDelayed({
Log.e(TAG, "btn1: handler runnable")
}, token,2000)
// 取消延时任务
//handler.removeCallbacksAndMessages(token)
*/
/*
// 创建CountDownTimer对象
Log.e(TAG, "demo2: CountDownTimer")
val intervalTime = 1000L// 倒计时间隔
val countDownTime = 3000L// 倒计时总时间
val countDownTimer: CountDownTimer = object : CountDownTimer(countDownTime, intervalTime) {
override fun onTick(millisUntilFinished: Long) {
// 倒计时执行中
Log.e(TAG, "btn1: onTick")
}
override fun onFinish() {
Log.e(TAG, "btn1: onFinish runnable")
// 倒计时执行完成
}
}
// 开始倒计时
countDownTimer.start()
// 取消倒计时
//countDownTimer.cancel()
*/
/*
Log.e(TAG, "demo3: scheduledExecutorService")
// 创建ScheduledExecutorService对象
val times = 0
val scheduledExecutorService = Executors.newScheduledThreadPool(1)
// 调度延时任务
val scheduledFuture:ScheduledFuture<*> = scheduledExecutorService.scheduleAtFixedRate({
// 执行任务
Log.e(TAG, "btn1: scheduledExecutorService runnable")
}, 1000,2000, TimeUnit.MILLISECONDS)// 延时1s 间隔2s
// 取消延时任务
//scheduledFuture.cancel(true)
*/
// 创建Timer对象
Log.e(TAG, "demo4: Timer")
val timer = Timer()
// 调度延时任务
val timerTask: TimerTask = object : TimerTask() {
override fun run() {
// 执行任务
Log.e(TAG, "btn1: TimerTask runnable")
val launchIntent = Intent(this@MainActivity.applicationContext, MainActivity::class.java)
// launchIntent.action = Intent.ACTION_MAIN
// launchIntent.addCategory(Intent.CATEGORY_LAUNCHER)
launchIntent.flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT
startActivity(launchIntent)
}
}
timer.schedule(timerTask,2000)
// 取消延时任务
//timerTask.cancel()
}
fun btn2(view: View?) {
}
}