简体   繁体   English

getActivity为空时如何终止线程

[英]How to terminate the Thread when getActivity becomes null

Generally for terminating the Thread , the following code is used: 通常用于终止Thread,使用以下代码:

 new Thread((new Runnable() { @Override public void run() { ........ if (getActivity == null) return; } } ).start(); 

In this code, Checking the getActivity is done only for one time. 在这段代码中,检查getActivity仅执行一次。 Is there any code, so that whenever getActivity becomes null, return is called on the thread from where it is called. 是否有任何代码,以便每当getActivity变为null时,就从调用它的线程上调用return。

You can catch the NullPointerException: 您可以捕获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();

You only must stop the Thread like: 您只需要像这样停止线程:

 new Thread((new Runnable() {

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

          }   
 }  ).start();

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

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