如何在WorkManager doWork()中显示吐司

时间:2019-06-01 16:14:32

标签: android-toast android-workmanager

如何在WorkManager中显示吐司做work()?

当我尝试时,它会抛出

public class HomeController : Controller
{
    private readonly IHubContext<ChatHub> chatHub;

    public HomeController(IHubContext<ChatHub> chatHub)
    {
        this.chatHub = chatHub;
    }

    // ...
}

2 个答案:

答案 0 :(得分:1)

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

您的asc方法将类似于:

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(); } 将在构造函数中可用。

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

答案 1 :(得分:0)

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

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