停止服务中的一个线程(Stopping a thread inside a service)

2019-07-19 06:12发布

我有一个线程服务中,我希望能够停止线程,当我按下buttonStop我的主要活动类。

在我的主要活动课,我有:

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; 
    }           
  }
}

而在我的服务类,我有:

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();
}

}

什么是停止的最好方法mythread

也就是,我已经停止了该服务的方式stopService(new Intent(this, MyService.class)); 正确?

Answer 1:

你不能阻止具有运行势不可挡循环这样一个线程

while(true)
{

}

要停止该线程,声明一个boolean变量和while循环条件下使用。

public class MyService extends Service {
      ... 
      private Thread mythread;
      private boolean running;



     @Override
     public void onDestroy()
     {
         running = false;
         super.onDestroy();
     }

     @Override
     public void onStart(Intent intent, int startid) {

         running = true;
       mythread = new Thread() { 
       @Override
       public void run() {
         while(running) {
                   MY CODE TO RUN;
                 }
         }
       };
     };
     mythread.start();

}


Answer 2:

你叫的一站式服务的onDestroy()方法。



文章来源: Stopping a thread inside a service