2017-09-14 3 views
1

응용 프로그램이 백그라운드에서 작동 중일 때 서버를 계속 실행하고 수신 대기하려면 어떻게해야합니까?Android 소켓이 백그라운드에서 연결됨

현재 오류가 발생합니다 : 대상 컴퓨터가 연결을 적극적으로 거부하기 때문에 연결할 수 없습니다.

나는 PC와 파이썬에서 안드로이드와 클라이언트에 서버를 가지고있다.

누구나 설명 할 수있는 것은 감사 할 것입니다. 내 서버 코드.

public class MainActivity extends Activity { 

private ServerSocket serverSocket; 

Handler updateConversationHandler; 

Thread serverThread = null; 

private TextView text; 

public static final int SERVERPORT = 8080; 

@Override 
public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    text = (TextView) findViewById(R.id.textView); 

    updateConversationHandler = new Handler(); 

    this.serverThread = new Thread(new ServerThread()); 
    this.serverThread.start(); 

} 

@Override 
protected void onStop() { 
    super.onStop(); 
    try { 
     serverSocket.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

class ServerThread implements Runnable { 

    public void run() { 
     Socket socket = null; 
     try { 
      serverSocket = new ServerSocket(SERVERPORT); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     while (!Thread.currentThread().isInterrupted()) { 

      try { 

       socket = serverSocket.accept(); 

       CommunicationThread commThread = new CommunicationThread(socket); 
       new Thread(commThread).start(); 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

class CommunicationThread implements Runnable { 

    private Socket clientSocket; 

    private BufferedReader input; 

    public CommunicationThread(Socket clientSocket) { 

     this.clientSocket = clientSocket; 

     try { 

      this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream())); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public void run() { 

      try { 

       String read = input.readLine(); 

       updateConversationHandler.post(new updateUIThread(read)); 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

    } 

} 

class updateUIThread implements Runnable { 
    private String msg; 

    public updateUIThread(String str) { 
     this.msg = str; 
    } 
    @Override 
    public void run() { 
     if (msg == null) { 
      text.setText(msg); 
     } 
     else{ 
      text.setText(msg); 
      createNotification(); 
     } 
    } 
} 
void createNotification() { 

    Intent intent = new Intent(this, MainActivity.class); 
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0); 

    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); 

    Notification noti = new NotificationCompat.Builder(this) 
      .setContentTitle("NOTIFICATION") 
      .setContentText("NOTIFICATION") 
      .setTicker("NOTIFICATION") 
      .setSmallIcon(android.R.drawable.ic_dialog_info) 
      .setLargeIcon(icon) 
      .setAutoCancel(true) 
      .setContentIntent(pIntent) 
      .build(); 

    NotificationManager notificationManager = 
      (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

    notificationManager.notify(0, noti); 
}} 

답변

1

Android에서 백그라운드 작업을 수행하려면 서비스를 사용해야합니다.

당신의 활동에
public class MyService extends Service { 

    public static final String START_SERVER = "startserver"; 
    public static final String STOP_SERVER = "stopserver"; 
    public static final int SERVERPORT = 8080; 

    Thread serverThread; 
    ServerSocket serverSocket; 

    public MyService() { 

    } 

    //called when the services starts 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     //action set by setAction() in activity 
     String action = intent.getAction(); 
     if (action.equals(START_SERVER)) { 
      //start your server thread from here 
      this.serverThread = new Thread(new ServerThread()); 
      this.serverThread.start(); 
     } 
     if (action.equals(STOP_SERVER)) { 
      //stop server 
      if (serverSocket != null) { 
       try { 
        serverSocket.close(); 
       } catch (IOException ignored) {} 
      } 
     } 

     //configures behaviour if service is killed by system, see documentation 
     return START_REDELIVER_INTENT; 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO: Return the communication channel to the service. 
     throw new UnsupportedOperationException("Not yet implemented"); 
    } 

    class ServerThread implements Runnable { 

     public void run() { 
      Socket socket; 
      try { 
       serverSocket = new ServerSocket(SERVERPORT); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      while (!Thread.currentThread().isInterrupted()) { 

       try { 

        socket = serverSocket.accept(); 

        CommunicationThread commThread = new CommunicationThread(socket); 
        new Thread(commThread).start(); 

       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 

    class CommunicationThread implements Runnable { 

     private Socket clientSocket; 

     private BufferedReader input; 

     public CommunicationThread(Socket clientSocket) { 

      this.clientSocket = clientSocket; 

      try { 

       this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream())); 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 

     public void run() { 

      try { 

       String read = input.readLine(); 

       //update ui 
       //best way I found is to save the text somewhere and notify the MainActivity 
       //e.g. with a Broadcast 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

     } 
    } 
} 

, 당신이 호출하여 서비스를 시작할 수 있습니다 :

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

    //will start the server 
    Intent startServer = new Intent(this, MyService.class); 
    startServer.setAction(MyService.START_SERVER); 
    startService(startServer); 

    //and stop using 
    Intent stopServer = new Intent(this, MyService.class); 
    stopServer.setAction(MyService.STOP_SERVER); 
    startService(stopServer); 
} 

을 또한 당신의 AndroidManifest.xml에 인터넷 권한을 선언해야 같은 서버에 대한
서비스는 보일 것이다 . 태그 위 줄에 다음 내용을 추가하십시오.

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
0

LAN 또는 인터넷 (WAN)에서 테스트 중이십니까?

현재 많은 휴대 전화 제공 업체가 연결된 장치에 공용 IP 주소를 할당하지 않고 사설 IP를 할당하므로 WAN에서 포트에 액세스 할 수 없기 때문에 장치가 서버 역할을 할 수 없습니다.

관련 문제