Search code examples
android-toastandroid-workmanager

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()

Solution

  • 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.