Scheduling recurring task in Android

前端 未结 5 2259
南方客
南方客 2020-11-22 09:12

I\'m designing an app that has a recurring task of sending presence to a dedicated server as long as the app is in foreground.

In my searches across the web I saw a

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 09:51

    I realize this is an old question and has been answered but this could help someone. In your activity

    private ScheduledExecutorService scheduleTaskExecutor;
    

    In onCreate

      scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
    
        //Schedule a task to run every 5 seconds (or however long you want)
        scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // Do stuff here!
    
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Do stuff to update UI here!
                        Toast.makeText(MainActivity.this, "Its been 5 seconds", Toast.LENGTH_SHORT).show();
                    }
                });
    
            }
        }, 0, 5, TimeUnit.SECONDS); // or .MINUTES, .HOURS etc.
    

提交回复
热议问题