How to set a timer in android

前端 未结 13 1714
天命终不由人
天命终不由人 2020-11-22 06:43

What is the proper way to set a timer in android in order to kick off a task (a function that I create which does not change the UI)? Use this the Java way: http://docs.ora

13条回答
  •  既然无缘
    2020-11-22 07:17

    I used to use (Timer, TimerTask) as well as Handler to kick off (time-consuming) tasks periodically. Now I've switched the whole to RxJava. RxJava provides Observable.timer which is simpler, less error-prone, hassle-free to use.

    public class BetterTimerFragment extends Fragment {
      public static final String TAG = "BetterTimer";
      private TextView timeView;
      private Subscription timerSubscription;
    
      @Override
      public View onCreateView(LayoutInflater inflater,
                               @Nullable ViewGroup container,
                               @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_timer, container, false);
      }
    
      @Override
      public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        timeView = (TextView) view.findViewById(R.id.timeView);
      }
    
      @Override
      public void onResume() {
        super.onResume();
    
        // Right after the app is visible to users, delay 2 seconds
        // then kick off a (heavy) task every 10 seconds.
        timerSubscription = Observable.timer(2, 10, TimeUnit.SECONDS)
            .map(new Func1() {
              @Override
              public String call(Long unused) {
                // TODO: Probably do time-consuming work here.
                // This runs on a different thread than the main thread.
                return "Time: " + System.currentTimeMillis();
              }
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1() {
              @Override
              public void call(String timeText) {
                // The result will then be propagated back to the main thread.
                timeView.setText(timeText);
              }
            }, new Action1() {
              @Override
              public void call(Throwable throwable) {
                Log.e(TAG, throwable.getMessage(), throwable);
              }
            });
      }
    
      @Override
      public void onPause() {
        super.onPause();
    
        // Don't kick off tasks when the app gets invisible.
        timerSubscription.unsubscribe();
      }
    }
    

提交回复
热议问题