2014-12-02 40 views
-2

我有一个类实现runnable与运行功能。Java/Android线程暂停错误

@Override 
public void run() 
{ 
    while(running) 
    { 
    // thread code goes here:: 
    threadCode();//// 
    // thread code ends here 
    try 
    { 
     Thread.sleep(10); 
    } 
    catch (InterruptedException e) 
    { 
     e.printStackTrace(); 
    } 
    } 
} 

现在我试图暂停线程,如果发生什么事情。 我试图使用wait()和notify(),但它崩溃了应用程序,之后我想出了使用“running”布尔值并将其设置为false作为暂停,然后返回true以恢复。 不幸的是,它仍然崩溃的应用程序。

它给我logcat致命的错误。

“无法创建内螺纹处理程序尚未调用Looper.prepare()”

有什么工作简单的方法来暂停一个线程? ;/ Thx

编辑: 它根本不是线程。 我发现它崩溃的地方。 它崩溃的警告对话框 这里是它的代码:

AlertDialog.Builder builder1 = new AlertDialog.Builder(c); 
     builder1.setTitle("Game over!"); 
    builder1.setMessage("You survived "+secs+"."+msecs+ " seconds."); 
    builder1.setCancelable(false); 
    builder1.setPositiveButton("Replay", 
      new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int id) 
     { 
      // intialStuff(); 
      dialog.cancel(); 
     } 
    }); 
    builder1.setNegativeButton("Rage quit", 
      new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int id) { 
      dialog.cancel(); 
     } 
    }); 

    AlertDialog alert11 = builder1.create(); 
    alert11.show(); 

我尝试在画布类 运行它,也许它不能在画布类工作? C是主要活动的背景。

+0

什么是您的logcat告诉你吗? – 323go 2014-12-02 14:41:35

回答

0

在Android上,线程的工作方式与常规的基于java的“主”程序不同。从UI线程跨越的线程应该使用Looper来自己使用,否则它们会回退到主UI线程的Looper。对于从run方法内部调用Looper.prepare()的查询,可能是其中的第一行。然而,从长期可扩展性和正确方法的角度考虑使用Loader或AsynchTask。

+0

你能举个例子吗? – hey 2014-12-02 14:45:55

+0

谷歌为“android asynctask教程” – Nazgul 2014-12-02 14:46:38

+0

问题不在线程上,它与alertDialog有关,我编辑了主要问题。 ; – hey 2014-12-02 15:29:57

0

有两个问题,第一个是我在AlertDialog的消息中设置了int值,这导致了崩溃。 解决方法是:

setMessage("You survived "+Integer.toString(secs)+"."+Integer.toString(msecs)+" seconds.") 

第二个问题和主要的,我不得不用投手使线程的AlertDialog不会崩溃。

第二次修复: 创建处理程序。

private Handler threadHandler = new Handler() 
{ 
     public void handleMessage(android.os.Message msg) 
     { 
      //Go to thread function 
      threadCode(); 
     } 
}; 

调用它的运行功能:

@Override 
public void run() 
{ 
    while(true) 
    { 
    try 
    { 
     Thread.sleep(10); 
     //handler 
     if(running) 
     threadHandler.sendEmptyMessage(0); 
    } 
    catch (InterruptedException e) 
    { 
     e.printStackTrace(); 
    } 
    } 
}