evt evt - 3 months ago 34
Android Question

Toast will not show before try/catch Thread.sleep()

I've got a curious problem when I try to

show();
my Toasts. You'll see below two Toasts separated by a
try/catch and Thread.sleep();
In this case the second Toast,
toast2
, will show up but
toast1
will not.

If I remove the
try/catch
both Toasts will show up with no problem.

I've seen elsewhere on SO that
toast.show();
makes a request on the UI Thread which can be conflicted by other operations. I'm wondering if that is the same problem I have here with the
Thread.sleep();
How can I solve this problem?

Thank you

TestService.java


///Debug - Show a Toast
// Toast does NOT show up
Toast toast1 = Toast.makeText(context,"Service Started", Toast.LENGTH_SHORT);
toast1.show();

//Try to sleep for roughly 2 seconds
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//Debug - Shows a Toast
Toast toast2 = Toast.makeText(context,"Sleep completed", Toast.LENGTH_SHORT);
toast2.show();

Guy Guy
Answer

In real life, you will probably have some logic instead of just "sleep", right? THe right android way of, per your example, starting a service would be through executing it on a worker thread. This will make sure you won't get an ANR.

your could would look something like:

    new AsyncTask<Void, Void, Void>() {

        @Override
        protected void onPostExecute(Void result) {
            Toast toast2 = Toast.makeText(context, "Sleep completed",
                    Toast.LENGTH_SHORT);
            toast2.show();
        }

        @Override
        protected void onPreExecute() {
            Toast toast1 = Toast.makeText(context, "Service Started",
                    Toast.LENGTH_SHORT);
            toast1.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Try to sleep for roughly 2 seconds
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;

        }

    }.execute();