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()
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()
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.
Also found alternative solution, worked for me as well:
@Override
public Result doWork() {
context.getMainExecutor().execute(() -> Toast.makeText(context, "Сас ))", Toast.LENGTH_LONG).show());
return Result.success(); // may be done with handler
}
But also i saved Context
variable to the classfield
Context context;
public BackgroundWorker(Context context, WorkerParameters workerParams) {
super(context, workerParams);
this.context = context;
}