繁体   English   中英

Android中的TimerTask Fragment错误

[英]TimerTask Fragment error in Android

我正在尝试运行具有TimerTask的代码,但遇到了一些错误。 我的MainActivity是http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/我正在调用一个片段来做一些具有这个Timertask的动画。 一切都工作正常,但当我从列表项中选择不同的片段时,我遇到了TimerTask错误。

public class MyTimerTask extends TimerTask {

    @Override
    public void run() {
       while(true)
       {try {
           Thread.sleep(1000);
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                updateTextView();

            }
        });
    }catch (InterruptedException e){
        e.printStackTrace();
    }

    }

 }

Logcat跟踪:

FATAL EXCEPTION: Timer-0
java.lang.NullPointerException at com.example.Project.HomeAnimation$MyTimerTask.run(HomeAnimation.java:53)
at java.util.Timer$TimerImpl.run(Timer.java:284)

你需要以某种方式停止while循环。 也许在onDestroy中将类标志设置为false,而while循环变为while(flag)

public class MyTimerTask extends TimerTask {

    @Override
    public void run() {
       flag = true;
       while(flag && (getActivity() != null))
       {try {
           Thread.sleep(1000);
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                updateTextView();

            }
        });
    }catch (InterruptedException e){
        e.printStackTrace();
    }

    }

 }

你的onDestroy方法看起来像:

public void onDestroy() {
    flag = false;
    super.onDestroy();
}

不要忘记在片段类中声明flag

private boolean flag = false;

您可以将HandlerRunnable结合使用:

 Handler hander = new Handler();


// Your runnable that will be triggered.
Runnable runnable = new Runnable() {
       public void run() {

           // do stuff

           // post it again
           handler.postDelayed(this, delay);
       }
    };

// Start
hander.post(runnable);


// Stop
handler.removeCallbacks(runnable);

如果您使用片段,最简单的方法是通过调用isVisible()方法检查当前片段是否可见:

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

                   // stuff to do

                }
            });
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM