title: Stop the service when the App is closed and not when the user changes the activity
body: <p>I have a trackingService <code>locationManager</code>  component which processes in the background and it is launched from the <code>MainActivity</code> activity. At the same time, I have another component to retrieve this data from the server and displaying it in the <code>Map</code> activity. The user can access data in the server from the MainActivity, when he clicks a buton in it. Thereupon, the data is being retrieved from the server and the user redirects to the <code>Map</code> activity. Everything it works for me so far.</p>
  
  <p>I am trying to remove the <code>locationManager</code> in two cases:</p>
  
  <ul>
  <li>When the user click the checkbox in the menu of  MainActivity.</li>
  <li>or when he closes the app (Not when the user changes the activity).</li>
  </ul>
  
  <p>With this code snippet:</p>
  
  <pre><code>@Override
  public void onDestroy() {
      super.onDestroy();
      unregisterReceiver(wifi_receiver);
      System.out.println("ABC TrackingService onDestroy() was invoked.");
      // commeted 13.08.15
  
      if(lm != null){
          lm.removeUpdates(this);
          System.out.println("ABC lm locationManager is not equal null.");
      }else{
          System.out.println("ABC lm locationManager is null.");
  
      }       
  }
  </code></pre>
  
  <p>I have tried it with the code below so when I click the button in the MainActivity for the first time, the user is being redirected to the <code>Map</code> activity and the service works (without calling the <code>onDestroy()</code> in the <code>TrackingService</code> class) but when I go back from the Map activity to the MainActivity(Service still works) and then clicks the button to go again to the <code>Map</code> activity, at this point, the <code>onDestroy()</code> in the <code>TrackingService</code> class is being called and the service stops </p>
  
  <p>With this code snippet:</p>
  
  <pre><code>@Override
  public void onDestroy() {
      super.onDestroy();
      unregisterReceiver(wifi_receiver);
      System.out.println("ABC TrackingService onDestroy() was invoked.");
      lm.removeUpdates(this);
  
  }
  </code></pre>
  
  <p>I am getting this error below:
  <strong>Error:</strong></p>
  
  <pre><code>08-29 12:46:06.624: E/AndroidRuntime(6332): FATAL EXCEPTION: main
  08-29 12:46:06.624: E/AndroidRuntime(6332): Process: com.bustracker, PID: 6332
  08-29 12:46:06.624: E/AndroidRuntime(6332): java.lang.RuntimeException: Unable to stop service com.bustracker.TrackingService@1e57ec95: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.location.LocationManager.removeUpdates(android.location.LocationListener)' on a null object reference
  08-29 12:46:06.624: E/AndroidRuntime(6332):     at android.app.ActivityThread.handleStopService(ActivityThread.java:3356)
  08-29 12:46:06.624: E/AndroidRuntime(6332):     at android.app.ActivityThread.access$2300(ActivityThread.java:177)
  08-29 12:46:06.624: E/AndroidRuntime(6332):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1551)
  08-29 12:46:06.624: E/AndroidRuntime(6332):     at android.os.Handler.dispatchMessage(Handler.java:102)
  08-29 12:46:06.624: E/AndroidRuntime(6332):     at android.os.Looper.loop(Looper.java:145)
  08-29 12:46:06.624: E/AndroidRuntime(6332):     at android.app.ActivityThread.main(ActivityThread.java:5944)
  08-29 12:46:06.624: E/AndroidRuntime(6332):     at java.lang.reflect.Method.invoke(Native Method)
  08-29 12:46:06.624: E/AndroidRuntime(6332):     at java.lang.reflect.Method.invoke(Method.java:372)
  08-29 12:46:06.624: E/AndroidRuntime(6332):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
  08-29 12:46:06.624: E/AndroidRuntime(6332):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
  08-29 12:46:06.624: E/AndroidRuntime(6332): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.location.LocationManager.removeUpdates(android.location.LocationListener)' on a null object reference
  08-29 12:46:06.624: E/AndroidRuntime(6332):     at com.bustracker.TrackingService.onDestroy(TrackingService.java:301)
  08-29 12:46:06.624: E/AndroidRuntime(6332):     at android.app.ActivityThread.handleStopService(ActivityThread.java:3339)
  08-29 12:46:06.624: E/AndroidRuntime(6332):     ... 9 more
  </code></pre>
  
  <p>How can I stop the service in this two cases and why onDestroy() not being invoked when I click the button for the first time?</p>
  
  <p>I appreciate any help.</p>
  
  <p><strong>MainActivity:</strong></p>
  
  <pre><code>public class MainActivity extends ActionBarActivity implements
          AsyncTaskCallback {
      TrackingService mService;
      boolean mBound = false;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.route_available);
          // Start the TrackingService class.
          Intent i = new Intent(this, TrackingService.class);
          startService(i);
      }
  
  
      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
          MenuInflater inflater = getMenuInflater();
          inflater.inflate(R.menu.main_menu, menu);
          System.out.println("test onCreateOptionsMenu was invoked.");
  
          return true;
      }
  
      @Override
      public boolean onPrepareOptionsMenu(Menu menu) {
          MenuItem checkable = menu.findItem(R.id.checkable_menu);
          checkable.setChecked(isChecked);
          return true;
      }
  
      // Start and stop the background service.
      @Override
      public boolean onOptionsItemSelected(MenuItem item) {
          switch (item.getItemId()) {
          case R.id.checkable_menu:
              if (isChecked = !item.isChecked()) {
                  item.setChecked(isChecked);
                  Intent i = new Intent(this, TrackingService.class);
                  startService(i);
                  System.out.println("test if onOptionsItemSelected");
              } else {
                  mService.stopTrackingService();
  
              }
              return true;
  
          default:
              return false;
          }
      }
  
  }
  </code></pre>
  
  <p><strong>TrackingService class:</strong></p>
  
  <pre><code>public class TrackingService extends Service implements AsyncTaskCallback,
          LocationListener {
      LocationManager lm;
      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
          detectLocation();
          return START_STICKY;
      }
      private void detectLocation() {
          // TODO Auto-generated method stub
          Toast.makeText(this, "Inside detectlocation()", Toast.LENGTH_SHORT)
                  .show();
          lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
          lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 0,
                  this);
          enableGPS(lm);
  
      }
      @Override
      public void onDestroy() {
          super.onDestroy();
          lm.removeUpdates(this);
          System.out.println("ABC locationManager is not equal null.");       
      }
  
      public void stopTrackingService(){
          lm.removeUpdates(this);
      }
  }
  </code></pre>
  
  <p><strong>Map activity:</strong></p>
  
  <pre><code>public class Map extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener{
      @Override
      protected void onDestroy() {
          super.onDestroy();
   // To stop the service when the user closed the app in the background and the map ativity was opened.      
          stopAlarm();
          Intent i = new Intent(this, TrackingService.class);
          stopService(i);
          System.out.println("ABC Map onDestroy() was invoked!");
  
      }
  
  }
  </code></pre>