title: Stopping a thread inside a service
body: <p>I have a thread inside a service and I would like to be able to stop the thread when I press the <code>buttonStop</code> on my main activity class.</p>
  
  <p>In my main activity class I have:</p>
  
  <pre><code>public class MainActivity extends Activity implements OnClickListener { 
    ...
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main); 
  
      buttonStart = (Button) findViewById(R.id.buttonStart);
      buttonStop = (Button) findViewById(R.id.buttonStop);
  
      buttonStart.setOnClickListener(this);
      buttonStop.setOnClickListener(this);
    }
  
    public void onClick(View src) {
      switch (src.getId()) {
      case R.id.buttonStart:
           startService(new Intent(this, MyService.class));
           break;
      case R.id.buttonStop:
           stopService(new Intent(this, MyService.class));
           break; 
      }           
    }
  }
  </code></pre>
  
  <p>And in my service class I have:</p>
  
  <pre><code>public class MyService extends Service {
    ... 
    @Override
    public IBinder onBind(Intent intent) {
      return null;
    }
  
   @Override
   public void onCreate() {
      int icon = R.drawable.myicon;
      CharSequence tickerText = "Hello";
      long when = System.currentTimeMillis();
      Notification notification = new Notification(icon, tickerText, when);
      Intent notificationIntent = new Intent(this, MainActivity.class);
      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,  notificationIntent, 0);
      notification.setLatestEventInfo(this, "notification title", "notification message", pendingIntent);     
      startForeground(ONGOING_NOTIFICATION, notification);
              ...
   } 
  
   @Override
   public void onStart(Intent intent, int startid) {
     Thread mythread= new Thread() { 
     @Override
     public void run() {
       while(true) {
                 MY CODE TO RUN;
               }
       }
     }
   };
   mythread.start();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>what is the best way to stop the <code>mythread</code>?</p>
  
  <p>Also is the way that I have stopped the service by <code>stopService(new Intent(this, MyService.class));</code> correct?</p>