【问题标题】:Android Toast started from Service only displays once从 Service 启动的 Android Toast 只显示一次
【发布时间】:2010-10-26 15:12:19
【问题描述】:

我有一个监控套接字连接的服务。当连接丢失时,它需要显示一个 Toast 通知用户它正在重新连接。这第一次工作正常。之后,我在日志中看到了 enqueueToast,但没有显示 toast。任何想法表示赞赏。我认为这将是一件容易添加的事情,但我一定遗漏了一些东西。

日志条目

INFO/NotificationService(118):enqueueToast pkg=com.abc 回调=android.app.ITransientNotification$Stub$Proxy@43f7b100 持续时间=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() ?您能否为这个方法提供更多背景信息。
  • 这从服务类中调用,该服务类已由首次显示给用户的 Activity 的 bindService 调用启动。我希望使用 runOnUiThread 调用来显示 toast,但我不知道如何在服务中使用它。

标签: android


【解决方案1】:

是的,您可以使用 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

【讨论】:

【解决方案2】:

解决办法

http://www.jjoe64.com/2011/09/show-toast-notification-from-service.html

你必须在onStartCommand 方法中创建一个Handler。然后在 onHandleIntent 方法中,您可以创建并显示 toast 通知

【讨论】:

    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多