更改变量后,是否必须重新启动?

我有一个长期运行的服务,由两个线程组成。

//MY SERVICE: if(userEnabledProcessOne) //Shared preference value that I'm getting from the settings of my app based on a checkbox processOneThread.start(); if(userEnabledProcessTwo) processTwoThread.start(); 

基本上,我通过复选框为用户提供启用/禁用这些进程的选项。 现在,如果用户在服务运行时决定禁用其中一个进程,是否需要使用更新的共享首选项重新启动我的服务? 像这样?

 //In the settings activity of my app public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if ( isChecked ) { // Change shared preferences to make the process enabled stopService(myService.class) startService(myService.class) } if (!isChecked) // Change shared preferences to make the process enabled stopService(myService.class) startService(myService.class) } 

现在我已经改变了我的共享首选项,我是否需要重新启动包含两个线程的服务? 我需要对线程做任何事吗? 这有效吗?

非常感谢,

Ruchir

嗯,这样做会泄漏太多的泄漏,你的Service类在一个Thread上运行,如果你调用stopSelf()并让我说他是唯一的运行保持MainThread活着然后它将停止让两个Thread s玩。

线程不依赖于服务,所以你所做的就是你的服务类中有一个Volatile boolean

  private volatile boolean killThreads = false;//guess in your case this //flag will be binded to the isChecked of the checkbox or even the //interface method 

当你想重启你的toggle killThreads = true; ,现在在你的Threads工作负载的实现中,你需要做的是,如果它们处于循环中,他们需要始终检查killThreads标志,如果它的真实死亡时间如果没有继续,如果不是循环,仍然需要在每个主要代码行之后不断检查该标志

 //in your Service class private volatile boolean killThreads = false; //we have jumped to your thread - i am creating a new instance while(!killThreads){ //if means if this flag is false keep your loop //hard code comes here } //or if you are not running a loop //in your run method you can constantly check for this flag like for(int i =0; i < 100; i++){ if(killThreads){ break;//or return if you like } //rest of the code } //after the loop you can also check again if(killThreads){ return; } 

只需在具体的代码行后检查标志

现在在你的活动中

  //In the settings activity of my app public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // Change shared preferences to make the process enabled //what you do here is you update killThreads with the isChecked //so find a way to bind your bind your Activity to Service class //there are tons of example on here 

希望能帮助到你