簡體   English   中英

getActivity為空時如何終止線程

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

通常用於終止Thread,使用以下代碼:

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

在這段代碼中,檢查getActivity僅執行一次。 是否有任何代碼,以便每當getActivity變為null時,就從調用它的線程上調用return。

您可以捕獲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();

您只需要像這樣停止線程:

 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