Search code examples
javaandroidmultithreadingexecutorandroid-11

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


i am using below code to run in background and in postexecute, but my question is, how can i do a onPrexecute like previously in AsyncTask, for example to be able to set visible a progressbar running: Code i used until now, but i get error for 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();
                }
            });
        }
    });

error is here"progressBar_main_activity.setVisibility(View.VISIBLE);" Error below:

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)


Solution

  • 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();
                    }
                });
            }
        });