2011-10-01 93 views
1

我正在使用示例應用程序中的線程。在我的應用程序中,我使用了3個線程在無限循環中運行。這3個線程用於android服務類。當我啓動這些線程時,線程正在運行並且UI不是允許直到完成無限循環。但我怎樣才能停止線程,我如何處理UI?如何從android服務停止無限循環線程?

我寫了一個服務類,如下所示:

ServiceApp.java

public class ServiceApp extends Service 
    { 
    @Override 
    public IBinder onBind(Intent arg0) { 
    return null; 
    } 

@Override 
public void onCreate() { 
    super.onCreate(); 

    while(true) 
    { 
    Thread child1=new Thread(new Runnable() { 

     @Override 
     public void run() { 

      try { 

       function1(); 

      } catch (InterruptedException e) { 

       e.printStackTrace(); 
      } 

     } 
    }); 

    child1.start(); 

    Thread child2=new Thread(new Runnable() { 

     @Override 
     public void run() { 

      try { 


       function2(); 



      } 
      catch (InterruptedException e) { 

       e.printStackTrace(); 
      } 
     } 
    }); 

    child2.start(); 


    Thread child3=new Thread(new Runnable() { 

     @Override 
     public void run() { 

      try { 


       function3(); 


      } catch (InterruptedException e) { 

       e.printStackTrace(); 
      }  
     } 
    }); 

    child3.start(); 

Toast.makeText(ServiceApp.this, "All threads started", Toast.LENGTH_SHORT).show(); 

} 
} 

public void function1() throws InterruptedException 
{ 
    Generic generic=new Generic(); //this for connect to web services 

    String add=generic.getAdd(10,20); 

    Log.v("function1", "addition from service"+add); 

    Thread.sleep(1000); 

} 

public void function2() throws InterruptedException 
{ 

    Generic generic=new Generic(); //this for connect to web services 

    String sub=generic.getSub(34,20); 

    Log.v("function2", "subtraction from service"+sub); 

    Thread.sleep(1000); 
} 

public void function3() throws InterruptedException 
{ 

    Generic generic=new Generic(); //this for connect to web services 

    String mul=generic.getMul(4, 6); 

    Log.v("function3", "multipicationn from service"+mul); 

    Thread.sleep(1000); 
} 

}

我怎麼能阻止child1,的child2,從活動類child3線程?

請任何身體幫我嗎?

回答

1

Service.onCreate()在UI線程內執行。你有一個無限循環,不斷創建越來越多的線程,所以UI沒有機會迴應用戶的行爲。如果你真的打算有這麼多的線程,你需要創建另一個線程來啓動原來的三個線程。

活動可以通過該服務或者通過粘結劑通信(你需要返回實際實現的null有代替),或通過發送意圖,您可以在Service.onStart()

捕捉和處理