Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了从服务开始的Android Toast只显示一次大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个监视套接字连接的服务.当连接丢失时,需要显示Toast,通知用户它正在重新连接.这是第一次工作正常.之后,我在日志中看到了enqueueToast,但是没有显示吐司.任何想法都赞赏我以为这会是一件容易的事情,但是我一定是缺少一些东西.

日志条目

调用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

大佬总结

以上是大佬教程为你收集整理的从服务开始的Android Toast只显示一次全部内容,希望文章能够帮你解决从服务开始的Android Toast只显示一次所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。