André
André

Reputation: 191

Android sequential execution of functions

I know Android UI is not really meant for executing functions and waiting for them to finish, however, I think there are use cases were it is required, like networking.

My problem is, I want to run a series of network operations that rely on each other and take a bit more time than the split second it takes to the next execution, so some waiting is in order:

  1. Start hotspot
  2. Get network interfaces and IP
  3. Start socket

Initially I tested that all is working using buttons, then it waited between my button presses. But now I'd like to automatize it. I googled but all I found are solutions with Async task, which is deprecated. I tried with threads and join, but that usually causes weird crashes in the runnable, and it is not very elegant. I wonder if there is another solution?

Upvotes: 1

Views: 710

Answers (2)

i30mb1
i30mb1

Reputation: 4786

The best thing you can do with SDK it's use Executors to run your work in background sequentially

        val newSingleThreadExecutor = Executors.newSingleThreadExecutor()
        newSingleThreadExecutor.execute {
            // 1...
        }
        newSingleThreadExecutor.execute {
            // 2...
        }

But if you want to touch the UI from background should create handler check if view's not null

        val handler = Handler(Looper.myLooper()!!)
        newSingleThreadExecutor.execute {
            handler.post {
                view?.visibility = View.GONE
            }
        }

Upvotes: 2

Dan Baruch
Dan Baruch

Reputation: 1093

How about something like this?

new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
          startHotspot();
          getNetworkInterfaceAndIP();
          startSocket();
         }
       }, 300);

Upvotes: 0

Related Questions