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

时间:2014-07-05 11:22:11

标签: java android multithreading

`//some method
Timer timer=new Timer();
    //Handler handler=new Handler();
    timer.scheduleAtFixedRate(new TimerTask()
    {
        public void run()
        {
            loadLayout();
        }

    }, 1000, 10000000);
 //end of method
 public void loadLayout()
 {
    li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    wm = (WindowManager) getSystemService(WINDOW_SERVICE);

    params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY |        WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
            WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
            PixelFormat.TRANSLUCENT);
    params.gravity = Gravity.RIGHT | Gravity.TOP;
    myview = li.inflate(R.layout.locked_layout, null);
    wm.addView(myview, params);
 }`     

如何在线程中调用WindowMananger.addView(viewGroup,layoutParams)方法? 请帮帮我!!!!!

1 个答案:

答案 0 :(得分:0)

我认为你的问题是你在单独的线程中调用WindowMananger.addView(viewGroup,layoutParams),你应该在UI线程中调用它。这段代码在Activity中,对吗?所以只需修改你的TimerTask:

Timer timer=new Timer();
//Handler handler=new Handler();
timer.scheduleAtFixedRate(new TimerTask()
{
    public void run()
    {       
       runOnUiThread(new Runnable() {

          @Override
          public void run() {
             loadLayout();
          }
      });
    }

}, 1000, 10000000);