Android Toast从服务启动时只显示一次

9
我有一个监控socket连接的服务。当连接丢失时,需要显示一个Toast通知用户正在重新连接。第一次这样做没问题。之后,我在日志中看到enqueueToast,但是Toast没有显示。欢迎提出任何想法。我认为这应该是一个简单的添加,但我可能漏掉了什么。
日志条目:
INFO/NotificationService(118): enqueueToast pkg=com.abc callback=android.app.ITransientNotification$Stub$Proxy@43f7b100 duration=1
调用Toast的代码:
public class ConnectionService extends Service 
{ .....

public void restartConnection()
{
  try
  {
     Log.i(this.toString(), "Attempting to reconnect...");

     // increase the wait between each retry until the max is reached
     int sleepTime = reconnectCounter * MIN_RECON_WAIT;

     if (sleepTime > MAX_RECON_WAIT)
     {
        sleepTime = MAX_RECON_WAIT;
     }

     String msg = "The connection has been lost.  Restart attempt will start in: " + sleepTime/1000 + " seconds";

     Log.i(this.toString(), msg);
     Toast.makeText(getApplicationContext(), msg , Toast.LENGTH_LONG).show();

     Thread.sleep(sleepTime);

     // increment the counter
     reconnectCounter++;

     this.startConnectionThread();

  }
  catch (Exception e)
  {
      Log.e(this.toString(), "Exception: " + e.toString());
      e.printStackTrace();
  }
}// end retartConnection

这可能是一个线程问题。你是从UI线程还是从另一个线程调用Toast.show()的?你能给这个方法提供更多的上下文吗? - Vuk
这是从Service类中调用的,该类已通过Activity中的bindService调用启动,并首先显示给用户。我希望使用runOnUiThread调用来显示toast,但我无法弄清楚如何在Service中使用它。 - bursk
2个回答

12

嗯,你可以选择使用runOnUiThread,这是一个合法的方法。
另外,你也可以尝试使用Handler替代方案。无论哪种方式都应该能够工作。

以下是我脑海中的一些代码。我现在没有SDK测试,但我认为它应该能给你一个大致的想法。

public class ConnectionService extends Service {  
  private Handler handler = new Handler();

  public void restartConnection(){
     int sleepTime = reconnectCounter * MIN_RECON_WAIT;
     if (sleepTime > MAX_RECON_WAIT)
     {
        sleepTime = MAX_RECON_WAIT;
     }
     String msg = "The connection has been lost.  Restart attempt will start in: " + sleepTime/1000 + " seconds";
     (new Timer()).schedule(
     new TimerTask() {
        public void run() {
           handler.post(new Runnable() {
              public void run() {
                 Toast.makeText(getApplicationContext(), "msg", Toast.LENGTH_LONG).show();
                 reconnectCounter++;
                 this.startConnectionThread()
              }
           });
        }
     }, sleepTime);
  }//end restartConnection

}//end ConnectionService

1
这不是一个好的解决方案。更好、更简单的方法是:http://www.jjoe64.com/2011/09/show-toast-notification-from-service.html - appsthatmatter
感谢您的有益帖子! - Warwicky

7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接