How do I kill an Android thread completely?

后端 未结 5 412
灰色年华
灰色年华 2020-12-03 01:20

I have a service that has its own thread running on background. I\'d like to kill that service including the thread.

I created the thread like this and run it.

相关标签:
5条回答
  • 2020-12-03 01:27

    use Context.stopService() or stopSelf() method of the Service.

    0 讨论(0)
  • 2020-12-03 01:31
    @Override
        protected void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            Thread.currentThread().interrupt();
        }
    
    0 讨论(0)
  • 2020-12-03 01:39

    to kill the thread , i think you can do like this :

    myService.getThread().interrupt();
    

    NOTE : the method Thread.stop() is deprecated

    EDIT : : try this

    public void stopThread(){
      if(myService.getThread()!=null){
          myService.getThread().interrupt();
          myService.setThread(null);
      }
    }
    
    0 讨论(0)
  • 2020-12-03 01:43

    Do it in the service's onDestroy method

    http://developer.android.com/reference/android/app/Service.html#onDestroy()

     public void onDestroy(){
    
             thread.stop();
             super.onDestroy(); 
     }
    

    Then stop the service with stopService(); (this will invoke onDestroy());

    http://developer.android.com/reference/android/content/Context.html#stopService(android.content.Intent)

    0 讨论(0)
  • 2020-12-03 01:50

    The method Thread.stop() is deprecated, you can use Thread.currentThread().interrupt(); and then set thread=null.

    0 讨论(0)
提交回复
热议问题