2013-02-11 48 views
0

我正在使用按钮在我的应用程序中启动后台服务。这是我正在使用的代码:在新主题中启动后台服务冻结主应用程序

@Override 
public void actionPerformed(ActionEvent action) { 
    if (action.getActionCommand().equals("Start")) { 
     while (true) { 
      new Thread(new Runnable() { 
       public void run() { 
        System.out.println("Started"); 
       } 
      }).start(); 

      try { 
       Thread.sleep(1000); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

这会每秒更新一次服务,这正是我想要的。问题是它冻结了应用程序的其余部分。我如何实现它,以便不会发生?

+0

你忘了'android'标记吗? – m0skit0 2013-02-11 12:51:58

+0

没有。标准Java。 – spacitron 2013-02-11 14:56:11

回答

1

下可能导致应用程序暂停:

while (true) { 
     ... 
    } 

尝试删除这些行。

编辑:根据意见,使新推出的螺纹火每秒,移动睡眠,而run()方法内循环:

if (action.getActionCommand().equals("Start")) { 
    new Thread(new Runnable() { 
     public void run() { 
      while (true) { 
       System.out.println("Started");  } 
       try { 
        Thread.sleep(1000); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    }).start(); 
} 
+0

删除“while”不会产生他想要的结果,也不会提供替代解决方案。 – m0skit0 2013-02-11 12:53:41

+0

已更新以尝试捕获该要求。 – Armand 2013-02-11 13:20:24

+0

我试过了。它给了我一个“无法访问的代码”错误。 – spacitron 2013-02-11 14:59:01

0

你调用线程这种方法这会更新GUI,而这正在暂停GUI刷新。产生一个新线程并在那里执行。

0

无限循环? while (true) {.....}

你应该如何离开这里 - 添加打印语句内循环,你会知道,你已经被困在这里按钮后点击

0

好吧我知道了。这是我应该做的:

@Override 
public void actionPerformed(ActionEvent action) { 
    if (action.getActionCommand().equals("Start")) { 
     new Thread(new Runnable() { 
      public void run() { 
       while (true) { 
        System.out.println("Started"); 
        try { 
         Thread.sleep(1000); 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
     }).start(); 
    } 
} 
+0

这就是我告诉你在我的回答中做的事情...... – m0skit0 2013-02-11 16:05:19

相关问题