软件引起的连接异常终止:从最近的列表中清除应用程序时出现套接字写入错误(它运行在与服务不同的线程中)

软件引起的连接异常终止:从最近的列表中清除应用程序时出现套接字写入错误(它运行在与服务不同的线程中)

问题描述:

我制作了一个应用程序,其中包含“开始”按钮,当它按下时,它会启动客户端线程服务,其中客户端Socket通过服务器套接字连接到我的PC,它运行良好,直到应用程序从最近列表中被清除。当我按下开始按钮并执行finish()关闭应用程序时,也不会发生同样的情况。该服务在两种情况下运行,但是当我从最近列表中清除应用程序时,服务将继续运行,但我在服务器应用程序中收到错误“软件导致连接中止:套接字写入错误”。当我使用finish()来关闭应用程序时,它也会从最近的列表中清除,但它会在没有套接字出现任何错误的情况下成功运行服务。软件引起的连接异常终止:从最近的列表中清除应用程序时出现套接字写入错误(它运行在与服务不同的线程中)

我该怎么办?

对不起,我的英语不是我的母语。

MainActivity.java

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

    Intent serviceIntent = new Intent(getBaseContext(), ClientService.class); 
} 

//This is called when I click the start button 
public void ServiceToggle(View v) { 
    if (!isServiceRunning(ClientService.class)) { 
     new Thread(new Runnable() { 
      @Override 
      public void run() { 
       startService(serviceIntent); 
      } 
     }).start(); 
    } else { 
     new Thread(new Runnable() { 
      @Override 
      public void run() { 
       stopService(serviceIntent); 
      } 
     }).start(); 
    } 
} 

ClientService.java

public class ClientService extends Service { 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     super.onCreate(); 
     handler = new Handler(); 
     new Thread(new Client()).start(); 

     return START_STICKY; 
    } 

    class Client implements Runnable { 
     String message; 

     @Override 
     public void run() { 
      try { 
       socket = new Socket(IP, PORT); 

       objectInputStream = new ObjectInputStream(socket.getInputStream()); 

       while (true) { 
        message = (String) objectInputStream.readObject(); 

        UpdateOnUI(message); 
       } 
      } catch(Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    public void UpdateOnUI(final String string) { 
     handler.post(new Runnable() { 
      @Override 
      public void run() { 
       Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show(); 
      } 
     }); 
    } 
} 

的误差是无法从服务器端(Windows)中客户端(Android)和是在问其他问题不同堆栈溢出。当应用程序从任务关闭时,此错误被抛出,服务继续运行,套接字在服务内部实现,当关闭活动而不是服务时也会出现。

+0

请添加活动和服务的代码。 –

+0

如果我在startService(serviceIntent)之后使用finish();在MainActivity中关闭应用程序,我谈到的错误不会发生。 –

+0

@Jens此消息的官方原因在复本中引用,无论您是否亲自知道。 – EJP

它现在有效。只需要在Foreground中使服务工作。由于一个愚蠢的错误,使它前台没有工作,我在另一个线程中执行它,但忘记执行它(没有调用.start())。