简体   繁体   中英

Thread.sleep does not pause the app in Android

I would like to pause my android app for 1 second after I inserted something into the Firebase database. For that I use the following code insider a liistener:

        firebase_DB.child(id).setValue(currentOrder).addOnCompleteListener(new OnCompleteListener<Void>() {
         @Override
            public void onComplete(@NonNull Task<Void> task) {
             if (task.isSuccessful()) {
                 orderSuccesfullyWritten[0] =true;
                 orderCouldNotBeSendAfterMutipleAttemps[0] = false;
                 Log.e("dbTAG",  "Data successfully written.");
                 try {
                     Thread.sleep(1000);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                } else {

                 Log.e("dbTAG", task.getException().getMessage());
                }
            }
    });

The code is being executed (and I get the message that "Data successfully written" but the Threas.sleep(1000) does not have any effects. The app just directly continues with the next actions. Any idea why this is the case? I'll appreciate every comment.

You are putting thread.sleep once the firebase query has already completed.

Simply move Thread.sleep to after your firebase query

firebase_DB.child(id).setValue(currentOrder).addOnCompleteListener(do something);
Thread.sleep(1000);

A firebase query runs asynchronously, meaning it is running on a background thread. So with this code the main thread will sleep for a second while the firebase query is executing

But be reminded that using Thread.sleep() is bad practice

Just some additional information why Thread.sleep() called on main thread is bad idea:

  1. You will block the main thread (UI thread) in which all of the UI stuff happens -> this means you screen will 'freeze' and this is bad UX (you can't put a loader even if you want to).
  2. If you block the main thread more than 5 seconds then you will get "app is not responding" screen, and OS will kill your app, and the user can lost data.

Basically I would like to pause the UI in case of not being able to submit the data to the firebase query.

I would suggest you to put a loading screen telling the user the data is uploading... or smth like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM