2011-10-01 5 views
1

난 샘플 응용 프로그램에서 스레드와 함께 일하고 있습니다. 내 응용 프로그램에서 3 스레드는 무한 루프에서 실행되고 있습니다.이 3 스레드는 안드로이드 서비스 class.when에서 이러한 스레드를 시작하는 다음 스레드가 실행되고 UI가 사용됩니다 무한 루프가 완료 될 때까지 기다리십시오.하지만 어떻게 스레드를 멈출 수 있고 UI를 처리 할 수 ​​있습니까? 다음과 같이어떻게 안드로이드 서비스에서 무한 루프 스레드를 막을 수 있습니까?

i는 서비스 클래스를 작성했습니다 :

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

}

내가 어떻게 활동 클래스의 자식 1, 자식 2, child3 스레드를 중지 할 수 있습니다?

시체를 도와주세요.

답변

1

Service.onCreate()은 UI 스레드 내에서 실행됩니다. 거기에 무한 루프가있어 점점 더 많은 스레드를 생성하므로 UI는 사용자의 동작에 응답 할 기회를 얻지 못합니다. 실제로 많은 스레드를 사용하려는 경우 원래 스레드를 시작하는 스레드를 다시 만들어야합니다.

활동 서비스와 중 바인더를 통해 통신 할 수 있습니다 또는 당신이 Service.onStart()

에서 캡처하고 처리 할 수있는 의도로 보내기 (대신이 null의 실제 구현을 반환해야합니다)