当getActivity变为null时如何终止Thread

时间:2014-01-08 07:23:08

标签: java android multithreading

通常,对于终止线程,使用以下代码:

new Thread((new Runnable() {

          @Override
          public void run() {
              ........
              if (getActivity == null) return;

          }   
 }  ).start();

在此代码中,仅检查getActivity一次。是否有任何代码,因此每当getActivity变为null时,将在调用它的线程上调用return。

2 个答案:

答案 0 :(得分:1)

您可以捕获NullPointerException:

new Thread((new Runnable() {

      @Override
      public void run() {
          try {
              while (true) {
                  ...
                  // reference null Activity. Throw NPE
                  ...
              }
          } catch (NullPointerException e) {
              Log.e(DEBUG, "Activity reference became null. Finishing thread.");
          }

      }   
}  ).start();

答案 1 :(得分:0)

你必须像以下一样停止线程:

 new Thread((new Runnable() {

          @Override
          public void run() {
              ........
              if (getActivity == null) return; //@tgkprog

          }   
 }  ).start();