Android AsyncTask API 在 Android 11 中弃用,使用 Executor 作为替代

Android AsyncTask API deprecating in Android 11, using Executor as alternative

我在后台和执行后使用下面的代码 运行,但我的问题是,我怎样才能像以前在 AsyncTask 中那样执行 onPrexecute,例如能够设置可见的进度条 运行宁: 我到目前为止使用的代码,但我收到 UI:

的错误
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Handler handler = new Handler(Looper.getMainLooper());

    executor.execute(new Runnable() {
        @Override
        public void run() {

            //Background work here
        progressBar_main_activity.setVisibility(View.VISIBLE);
        runbackground();    
        
            handler.post(new Runnable() {
                @Override
                public void run() {
                    //UI Thread work here
          update_UI();
                }
            });
        }
    });

这里有错误progressBar_main_activity.setVisibility(View.VISIBLE);" 错误如下:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.         at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:8205)         at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1426)

ExecutorService executor = Executors.newSingleThreadExecutor();
    Handler handler = new Handler(Looper.getMainLooper());

//onPreExecute() before to get into executor, as below
progressBar_main_activity.setVisibility(View.VISIBLE);


    executor.execute(new Runnable() {
        @Override
        public void run() {

            //Background work here
        runbackground();    
        
            handler.post(new Runnable() {
                @Override
                public void run() {
                    //UI Thread work here
          update_UI();
                }
            });
        }
    });