在 Android 中创建每小时运行一次的线程的最佳实践?

Best practice to create a thread that runs every hour in Android?

所以我试图在 Android 应用程序中创建需要每小时 运行 的后台任务。这是一项相当繁重的任务,大约需要 5 - 10 分钟才能完成,现在 运行s 在 UI 线程上,这当然不好,因为它会挂起整个应用程序。我在我的 MainActivity onCreate 中尝试了以下操作:

new Thread(new Runnable() {

    private Handler HeavyTaskHandler = new Handler(Looper.getMainLooper());

    public void run(){
        final TextView updatedTxt = findViewById(R.id.txt);
        updatedTxt.post(new Runnable() {
            @Override
            public void run() {
                updatedTxt.setText("Performing cleanup..");
            }
        });

        HeavyTask(); // <-- This method runs for 5 - 10 minutes

        updatedTxt.post(new Runnable() {
            @Override
            public void run() {
                updatedTxt.setText("Done..");
            }
        });

        HeavyTaskHandler.postDelayed(this, HeavyTaskCycle);
    }
}).start();

以上我有两个问题

我最终从 MainActivity 执行了以下操作,它没有挂起应用程序

private void CreateCleanUpThread()
{
    CleanUpThread = new Thread(new Runnable() {

        public void run(){
            try {
                while(true) {
                    performingCleanup = true;
                    final TextView updatedTxt = findViewById(R.id.updated_txt);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updatedTxt.setText("Performing database history cleanup..");
                        }
                    });

                    HeavyTask(); // <-- This method runs for 5 - 10 minutes

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updatedTxt.setText("Done..");
                        }
                    });
                    performingCleanup = false;
                    Thread.sleep(CleanUpCycle); // 1 hour wait time
                }
            } catch(Exception ex) {
                System.out.println("Error in CreateCleanUpThread : " + ex.getMessage());
            }
        }
    });
}

// onCreate in MainActivity
...
CleanUpThread.start();

当然不是最好的方法,但它行得通,现在就行。我认为应该改为服务。