如何实现仅在应用程序处于前台且仅一次运行1个线程时运行的后台任务?

我的应用程序位于前台时,我想定期(也许每5-10分钟一次)获取当前日期。当应用程序在后台运行时,我不在乎当前日期,因此我不想浪费任何电话资源。

我的第一个方法

我了解了很多有关如何处理此任务的知识,并且在大多数情况下,建议使用ScheduledThreadPoolExecuter。因此,我的方法如下(整个代码在Mainactivity.java中):

1。创建一个实现Runnable的类:

class UpdateDateRunnable2 implements Runnable {

        @Override
        public void run() {
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                currentDate = Calendar.getInstance().getTime();
                String date = sdf.format(currentDate);
                Log.d("THREAD",date);
        }
    }

2。在onCreate方法中实现此代码:

        executor = new ScheduledThreadPoolExecutor(1);
        executor.scheduleAtFixedRate(new UpdateDateRunnable2(),1,TimeUnit.SECONDS);

我将延迟设置为1秒,只是为了查看一切是否正常工作。

3。在onDestroy方法中实现此代码:

executor.shutdownNow();

我的问题如下:

  1. 这是执行后台任务的正确方法吗?

  2. 当应用程序不在前台时如何停止后台任务的执行(因此该应用程序不需要资源)

  3. 打印两次当前日期的后台线程是否从不创建两次是100%安全的吗?我不希望(例如)应用程序每次旋转显示器时都创建其他运行线程。据我了解,当旋转显示器时,该应用程序“杀死”了我当前的线程,但此后立即创建了一个新线程。那是对的吗?因此,在旋转一圈之后实际上将有2个线程,但是没有使用第一个线程,因此只有第二个线程使用了资源,对吗?

我的第二种方法

1。创建一个实现Runnable的类:

class UpdateDateRunnable implements Runnable {
        int seconds;

        UpdateDateRunnable(int seconds) {
            this.seconds = seconds;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                    currentDate = Calendar.getInstance().getTime();
                    String date = sdf.format(currentDate);
                    Log.d("THREAD",date);
                    Thread.sleep(seconds*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return;
                }
            }
        }

    }

2。在onCreate方法中实现此代码:

        runnable = new UpdateDateRunnable(1);
        updateDateThread = new Thread(runnable);
        updateDateThread.start();

3。在onDestroy方法中实现此代码:

updateDateThread.interrupt();

其他问题:

  1. 哪种方法更好/更“行业标准”?

  2. 只有一个正在运行的线程时,哪种方法更安全?

muma96132 回答:如何实现仅在应用程序处于前台且仅一次运行1个线程时运行的后台任务?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3119222.html

大家都在问