无法从非活动类(Android)显示吐司

时间:2016-12-25 19:51:28

标签: android android-activity toast

我写了一个消息传递应用程序,我想在其他用户发送消息时通知用户。但我无法在我的ContactListActivity中跟踪它,所以我尝试在我的connection.java类中显示它。(简单地说,如果新消息到达,则在查看contactList时弹出文本)。这是我试图做的事情

private  final Context mApplicationContext;
public Connection(context c){
 mApplicationContext = c.getApplicationContext();
/....
}
  System.out.println("Print something");
  Toast.makeText(mApplicationContext, " You received a  message from "+contactJid, Toast.LENGTH_LONG).show(); //Is called everytime when I receive a message.
  System.out.printnl("Print something");  // I can print both, I receive the message but toast does not appear

不要担心变量名称。我怎样才能实现目标?我在其他地方使用mApplicationContext,它可以做我想做的事。

我还试过在这个类中创建一个新的ContactListActivity对象并获得它的应用程序上下文也失败了 我很欣赏建设性的反馈,因此我可以更清楚地提出问题。

1 个答案:

答案 0 :(得分:1)

如果您在日志中获得响应,则可能是非UI线程的问题。工作线程在UI上不会更新或显示任何内容,因此只能从主线程更新UI。

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
    @Override
    public void run() {
    //Here you can update your UI
    }
});
相关问题