android中执行定时任务的几种方式

* handler
    private Handler handler;
    private Runnable task = new Runnable() {
      @Override
      public void run() {
        Log.i(TAG, "task thread: " + Thread.currentThread().getName()); // main
        if (handler != null) {
          handler.postDelayed(this, 1000L);  // 继续循环
        }
      }
    };
      private void fun4() {
        handler = new Handler();
        handler.postDelayed(task, 1000L); // 1s后执行
        
        btn2.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
          handler.removeCallbacks(task);  // 停止执行
        }
      });
      }
  * AlarmManager
    AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
		manager.setRepeating(AlarmManager.RTC_WAKEUP, 1000L, 1000L, pi);
  * Timer
    Timer senderTimer = new Timer();
		senderTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				sendProbeData();
			}
		}, 1000L, 1000L);

你可能感兴趣的:(thread,android,timer,manager,service,任务)