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()
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.
You can't show a Toast on a thread that is not the activity's ui thread.
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.
Toast class. The show() method is used to display the toast notification. Syntax: Toast toast = Toast.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With