2011-10-01 59 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()

捕捉和处理