0

I have implemented a method to send data to a server but I want to delay the implemented functions failure message around 20 milliseconds ,

my code is

public void onFailure(Call call, IOException e) {
              
                call.cancel();
                Log.d("FAIL", e.getMessage());

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView responseText = findViewById(R.id.responseText);
                        responseText.setText("Failed to Connect to Server. Please Try Again.");
                    }
                });
            }
  • 1
    Does this answer your question? [How to call a method after a delay in Android](https://stackoverflow.com/questions/3072173/how-to-call-a-method-after-a-delay-in-android) – denvercoder9 Jun 22 '20 at 09:24
  • It dosen't work on runOnUiThred – Dilan nadeesha Jun 22 '20 at 09:26
  • 1
    delaying the UI Thread is something you should never do. Put the failure method in a separate Thread like ASyncTask or use a Handler or similar and delay it there. – A Honey Bustard Jun 22 '20 at 09:34
  • @AHoneyBustard but no one is delaying the UI thread here, the case here is more about delaying an action and execute it after some time rather than freezing the UI thread :) – Mariusz Brona Jun 22 '20 at 09:37
  • @Mariusz Brona I know, but the question can easily be interpreted otherwise... – A Honey Bustard Jun 22 '20 at 09:40

1 Answers1

2

You can use this:

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        TextView responseText = findViewById(R.id.responseText);
        responseText.setText("Failed to Connect to Server. Please Try Again.");
    }
}, 20)

new Handler(Looper.getMainLooper()) and runOnUiThread {} are doing basically the same, but are executed a little bit differently. For your usecase the first option is a nice fit since it allows a delay. A little more explanation you can find here:

runOnUiThread vs Looper.getMainLooper().post in Android

Mariusz Brona
  • 1,549
  • 10
  • 12