gpt4 book ai didi

从 Service 启动的 Android Toast 只显示一次

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:23:50 24 4
gpt4 key购买 nike

我有一个监控套接字连接的服务。当连接丢失时,它需要显示一个 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

最佳答案

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

关于从 Service 启动的 Android Toast 只显示一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4025082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com