【问题标题】:Display toast from a thread into main activity将 toast 从线程显示到主要活动中
【发布时间】:2014-04-11 09:50:18
【问题描述】:

我正在创建一个 Android 应用程序,在其中我从主要活动 A 调用服务 C。从服务 C 我正在调用扩展线程的类 B 的实例。现在我需要为这个 B 类的用户显示一条消息。我尝试使用 Handler 类,我使用的代码是

在 B 类扩展线程中:

Message status = someHandler.obtainMessage();
        Bundle data = new Bundle();
        data.putString("SOMETHING", "dist");
        status.setData(data);

        someHandler.sendMessage(status);

在服务 C:

Handler someHandler = new Handler(){

     //this method will handle the calls from other threads.       
     public void handleMessage(Message msg) {

          Toast.makeText(getBaseContext(), msg.getData().getString("SOMETHING"),Toast.LENGTH_SHORT).show();
     }
};

现在,当我运行它时,我希望在主 UI 活动 A 中显示一个 toast。但它不起作用。

【问题讨论】:

  • “不工作”不是一个非常有用的故障报告——它可能不足以让读者找出问题所在——所以这个老问题可能会因为缺少minimal reproducible example 而被关闭。万一您仍然需要答案,请编辑问题以包含更多详细信息。

标签: android multithreading service android-toast


【解决方案1】:

它可能是上下文,取决于服务 C 的显示方式,getBaseContext() 并不总是正确的。您可以尝试“this”或静态调用上下文。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多