1

Generally for terminating the Thread , the following code is used:

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. Is there any code, so that whenever getActivity becomes null, return is called on the thread from where it is called.

Shanki Bansal
  • 1,681
  • 2
  • 22
  • 32

2 Answers2

1

You can catch the 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();
Mike Ortiz
  • 4,031
  • 4
  • 27
  • 54
  • I cant to use try catch as : 1. NullPointerException may be occours not only by getActivity, but also by code written in that thread. 2. I have used Jar File in my project, some of the threads are envoked from there. Also it's not a good pratice to use try catch. So, I avoid such solutions, want to know if there is any better solution.Thanks for responding – Shanki Bansal Jan 08 '14 at 12:35
  • Using try-catch isn't bad practice. It's better than crashing. Your alternative is sprinkling `if (activity == null)` statements everywhere. – Mike Ortiz Jan 08 '14 at 16:48
0

You only must stop the Thread like:

 new Thread((new Runnable() {

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

          }   
 }  ).start();
Mert
  • 1,333
  • 1
  • 12
  • 15
  • 1
    jvm has no reliable way to stop a thread. To stop or interrupt a thread, the target thread needs to cooperate by entering some interrupt-able state, such as sleep() or wait(). You should not use stop() as it has been deprecated. – Saurabh Sharma Jan 08 '14 at 07:30
  • This is deprecated as of API 1. [See here](http://developer.android.com/reference/java/lang/Thread.html#stop()). It also doesn't answer the question of how to exit the thread as soon as Activity becomes null. – Mike Ortiz Jan 08 '14 at 07:33
  • when you have control of the run method there is no need to forceably stop it. Returning from it stops it. Even if you dont have control stop is deprecated and should only be used when you have some 3rd party code that you cannot change, as a last resort – tgkprog Jan 08 '14 at 08:45