2014-09-05 2 views
1

나는 서비스의 파괴까지, 활동적인 소켓을 유지하기 위해 서비스를 사용할 수 있었다면 궁금 해서요? '잘 배웠던 것은 매우 흥미 롭습니다. 또한 소켓 연결 상태를 나타내는 알림을 추가 할 수 있습니다. 소켓을 사용하여 서비스를 빌드하는 방법을 이해하는 경우에만 표시 할 수있는 예제가 있습니까? 나는 사전에소켓 서비스 + 통보

PS 감사합니다 : I에 유래에 보았다 그러나 나는 많은 설명 예

답변

2

당신은 바로 Service는 작업에 적합한 도구입니다 가정에 발견하지 않았습니다.

Services | Android Developers

서비스가 백그라운드에서 실행 시간이 긴 작업을 수행 할 수 있으며, 사용자 인터페이스를 제공하지 않는 응용 프로그램 구성 요소입니다 참조하십시오.

소켓 유지는 장기간 백그라운드 작업을 수행 할 수 있습니다.

나는 다음을 수행하는 사용자를 위해이 예제를 만들어 :

  • 가/연결 다시 연결하고 독서에 대한 Thread을 시작합니다 InputStream
  • 신고 Notification
  • 닫기에서 현재 연결 상태 onCreate()에서 SocketThread을 중지하십시오. onDestroy()

import android.app.Service; 
import android.content.Intent; 
import android.os.IBinder; 
import android.support.v4.app.NotificationCompat; 
import android.support.v4.app.NotificationManagerCompat; 

import java.io.IOException; 
import java.io.InputStream; 
import java.net.InetSocketAddress; 
import java.net.Socket; 
import java.net.UnknownHostException; 

public class MyService extends Service implements Runnable { 

    private static final int NOTIFICATION_ID = 1; 

    private boolean mRunning = false; 
    private Thread mThread; 

    private Socket mSocket; 
    private InputStream mInputStream; 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

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

     setNotificationMessage("Service created"); 

     if (mThread == null) { 
      mRunning = true; 

      mThread = new Thread(this); 
      mThread.start(); 
     } 
    } 

    @Override 
    public void run() { 
     try { 
      while (mRunning) { 
       try { 
        setNotificationMessage("Connecting"); 

        mSocket = new Socket(); 
        mSocket.connect(new InetSocketAddress("192.168.56.1", 9899)); 

        mInputStream = mSocket.getInputStream(); 

        setNotificationMessage("Connected"); 

        for (int c = mInputStream.read(); c > -1; c = mInputStream.read()) { 
         setNotificationMessage("Connected: " + (char) c); 
        } 
       } catch (UnknownHostException ignored) { 
        setNotificationMessage("Unknown host"); 
       } catch (IOException ignored) { 
        setNotificationMessage("Disconnected"); 
        close(); 
       } 

       try { 
        // Reconnect delay 
        Thread.sleep(1000); 
       } catch (InterruptedException ignored) { 
       } 
      } 
     } finally { 
      // Will eventually call onDestroy() 
      stopSelf(); 
     } 
    } 

    private void setNotificationMessage(CharSequence message) { 
     NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
     builder.setSmallIcon(R.drawable.ic_launcher); 
     builder.setContentTitle("Connection status"); 
     builder.setContentText(message); 

     NotificationManagerCompat nm = NotificationManagerCompat.from(this); 
     nm.notify(NOTIFICATION_ID, builder.build()); 
    } 

    private void close() { 
     if (mInputStream != null) { 
      try { 
       mInputStream.close(); 
       mInputStream = null; 
      } catch (IOException ignored) { 
      } 
     } 

     if (mSocket != null) { 
      try { 
       mSocket.close(); 
       mSocket = null; 
      } catch (IOException ignored) { 
      } 
     } 
    } 

    @Override 
    public void onDestroy() { 
     if (mThread != null) { 
      mRunning = false; 

      close(); 

      while (true) { 
       try { 
        mThread.interrupt(); 
        mThread.join(); 
        mThread = null; 
        break; 
       } catch (InterruptedException ignored) { 
       } 
      } 
     } 

     setNotificationMessage("Service destroyed"); 

     super.onDestroy(); 
    } 
} 
+0

방법은 무엇입니까 스레드의 조인 MyService.java? –

+1

Join은 스레드의 실행이 완료 될 때까지 대기합니다. [Thread | Android 개발자] (http://developer.android.com/reference/java/lang/Thread.html#join()) – Nicklas