【发布时间】: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