Stopping a thread inside a service

前端 未结 2 1033
借酒劲吻你
借酒劲吻你 2021-01-02 23:22

I have a thread inside a service and I would like to be able to stop the thread when I press the buttonStop on my main activity class.

In my main activi

2条回答
  •  庸人自扰
    2021-01-03 00:08

    You can't stop a thread that has a running unstoppable loop like this

    while(true)
    {
    
    }
    

    To stop that thread, declare a boolean variable and use it in while-loop condition.

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

提交回复
热议问题