【问题标题】:Java/Android Thread pause errorJava/Android 线程暂停错误
【发布时间】:2014-12-02 14:37:49
【问题描述】:

我有一个使用 run 函数实现 runnable 的类。

@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() 但它使应用程序崩溃,之后我想到使用“正在运行”布尔值并将其设置为 false 作为暂停,然后返回 true 以恢复。 不幸的是,它仍然使应用程序崩溃。

它给了我在 logcat 上的致命错误。

“无法在未调用 Looper.prepare() 的线程内创建处理程序”

有什么简单的方法可以暂停线程吗? ;/ 谢谢

编辑: 这根本与线程无关。 我发现它崩溃的地方。 它在警报对话框中崩溃 这是它的代码:

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 是主要活动的上下文。

【问题讨论】:

  • 你的 logcat 告诉你什么?

标签: java android multithreading


【解决方案1】:

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

【讨论】:

  • 问题不在线程上,它与alertDialog有关,我编辑了主要问题。 ;o
  • 在此处发布 logcat 或异常跟踪。
【解决方案2】:

有 2 个问题,首先是我在导致崩溃的 AlertDialog 的消息上设置了 int 值。 解决方法是:

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

第二个问题也是主要问题,我不得不在线程上使用hander,这样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();
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 2011-08-08
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多