Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to show toast in WorkManager doWork()

how to show toast in WorkManager do work()?

When I try, it throws

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
like image 970
Nurseyit Tursunkulov Avatar asked Jun 01 '19 16:06

Nurseyit Tursunkulov


People also ask

How do I show toast in activity?

Display the created Toast Message using the show() method of the Toast class. The code to show the Toast message: Toast. makeText(getApplicationContext(), "This a toast message", Toast.

Can I show toast from background thread?

You can't show a Toast on a thread that is not the activity's ui thread.

Which method is used to display toast?

Use the makeText() method, which takes the following parameters: The application Context . The text that should appear to the user. The duration that the toast should remain on the screen.

Which class displays a toast message on the screen?

Toast class. The show() method is used to display the toast notification. Syntax: Toast toast = Toast.


1 Answers

You can create Handler to show Toast on UI thread.

Your doWork method will be like:

@NonNull
@Override
public Result doWork() {
    Log.d(TAG, "doWork for Sync");

    Handler handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // Run your task here
            Toast.makeText(mContext, "Testing", Toast.LENGTH_SHORT).show();
        }
    }, 1000 );

    return Result.success();
}

Note : mContext will be available in Constructor.

Hope it will help you. Thank you.

like image 164
Pratik Butani Avatar answered Oct 01 '22 23:10

Pratik Butani