更改Fragment时TimerTask崩溃

时间:2014-04-23 10:06:06

标签: android multithreading android-fragments timer ui-thread

我在我的app的一个片段中运行了TimerTask;当我尝试使用" fragmentManager.beginTransaction()将dinamically切换到另一个片段时。替换"方法我的应用程序崩溃。 我确定我的问题与Timer bucause有关,如果我评论它一切正常。 这是片段中的Timer代码:

     public void startTimer(ProgressBar b){
     final ProgressBar bar = b;
      t = new Timer();   
      task = new TimerTask() {

        @Override
       public void run() {
        getActivity().runOnUiThread(new Runnable() {

          @Override
         public void run() {
              bar.setMax(3600);
          bar.setProgress(mytime);
          //TextView tv1 = (TextView) getView().findViewById(R.id.textView2);
          //tv1.setText("TIME LEFT:" +time);
          if (mytime <= 3600)
           mytime += 1;
          else {
           //tv1.setText("GAME OVER");           
          }
         }
        });
       }
      };
      t.scheduleAtFixedRate(task, 0, 1000);
     }

当我在UiThread上运行TimerTask时,我可能无法改变片段? 谢谢你的回答。

3 个答案:

答案 0 :(得分:1)

使用Handler Thread代替Timer任务。

处理程序线程是从UI线程创建的单独线程。所以它可以与UI线程交谈,你可以改变Activity / Fragment。

确保在更改片段

之前删除对处理程序的所有回调 像这样:

    final Handler handler=new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {
            if(condition)
            {
                handler.removeCallbacks(this);
            }
            else
            {
                handler.postDelayed(this,3600);
            }
        }
    }, 3600);

答案 1 :(得分:0)

如果为同一任务安排了两次计时器,它可能会崩溃。而且,为了从计时器任务更新UI,您可能必须使用处理程序

参考: Android timer updating a textview (UI)

答案 2 :(得分:0)

来自文档:replace()

Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.

您的片段在调用replace()后被销毁,我认为您应该使用方法addToBackStack()或使用hide()方法或使用onDestroy()方法停止计时器。