如何在 WorkManager doWork() 中显示 toast

how to show toast in WorkManager doWork()

如何在 WorkManager do work() 中显示 toast?

当我尝试时,它抛出

Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

您可以创建 Handler 以在 UI 线程上显示 Toast。

您的 doWork 方法如下:

@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();
}

注意:mContext 将在 Constructor 中可用。

希望对您有所帮助。谢谢。

还找到了替代解决方案,对我也有效:

@Override
public Result doWork() {
    context.getMainExecutor().execute(() -> Toast.makeText(context, "Сас ))", Toast.LENGTH_LONG).show());
    return Result.success();   // may be done with handler
}

但我也将 Context 变量保存到类字段

Context context;

public BackgroundWorker(Context context, WorkerParameters workerParams) {
    super(context, workerParams);
    this.context = context;
}