1

서비스를 호출하는 활동을 만들었으며 서비스는 서버와 데이터를 송수신하는 스레드를 만들고 다른 응용 프로그램과 서비스를 열고 스레드는 정상적으로 실행되지만 작업을 닫으면 서비스는 계속 실행되지만 스레드는 작동을 멈 춥니 다. 왜??? 스레드를 계속 실행하려면 어떻게해야합니까 !!활동을 닫을 때 내 서비스에서 생성 된 스레드가 종료 됨

코드

활동

package com.connectus.app; 

public class ConnectUsActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_connect_us); 

     Intent startServiceIntent = new Intent(getApplicationContext(), ConnectUsService.class); 
     startService(startServiceIntent); 
} 

서비스

package com.connectus.app; 

public class ConnectUsService extends Service { 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    // TODO Auto-generated method stub 

        Thread t=new Thread(new Runnable() { 

        private DataInputStream in; 
        private BufferedReader br; 
        private DataOutputStream out; 

        @Override 
        public void run() { 
         Socket server=null; 
         try{ 
          server=new Socket("10.10.40.58",4444); 
          in = new DataInputStream(server.getInputStream()); 
          br=new BufferedReader(new InputStreamReader(in)); 
          out = new DataOutputStream(server.getOutputStream()); 
          while(true){ 
           out.writeUTF("aaaaa"); 
           String leido=in.readUTF(); 

           out.writeUTF("asdf"); 
                    Thread.sleep(60000); 
          } 
         }catch(IOException ioe){ 
          ioe.printStackTrace(); 
         }catch (Exception e) { 
          e.printStackTrace(); 
         } 
        } 
       }); 
       t.start(); 


    return START_STICKY; 
} 

@Override 
public IBinder onBind(Intent arg0) { 
    // TODO Auto-generated method stub 
    return null; 
} 

} 

이 내 코드의 단지 부분은, 나는 그것이 도움이되기를 바랍니다.

+2

버그가 있어야합니다. 관련 코드를 게시하십시오. – Merlevede

+0

하지만 Logcat에서 오류가 표시되지 않습니다. 코드를 입력 해 보겠습니다. –

+0

우리에게 코드를 보여주십시오 – cheloncio

답변

0

모두에게 감사드립니다. 마침내 해결책을 찾았습니다. 그것은 setForeground 등() 메소드를 사용하는 모든 necesary했다, 난 그냥 내 서비스 클래스에이 코드를 추가 :

Notification note=new Notification(); 
startForeground(1337, note); 

내 연구에 따르면,이 코드는 서비스 자체에 의해 살해 당할 것을 방지하기 위해 사용된다.

최고!

+0

서비스는 결코 스스로를 죽이지 않으며, 기술적으로 멈추거나 안드로이드가 멈추게 할 수 있습니다. 전경 서비스는 서비스가 종료되는 것을 막지 않으며, 단지 이런 일이 발생할 가능성을 크게 줄입니다. 안전 측면에 관한 코드는 최악의 경우를 가정합니다. –

관련 문제