I've made an app in which I have Start button and when I press it, it starts the Client Thread Service in which the client Socket connects to my PC through Server Socket and it runs well till the app is cleared from recent list. The same doesn't happen when I press Start button and execute finish()
to close the app. The Service runs in both cases but when I clear the app from recent list, the Service keeps running but I receive an error in my Server App "Software caused connection abort: socket write error". And when I use finish()
to close the app, it also gets cleared from recent list but it the service keeps running service successfully without the socket getting any error.
What should I do??
And Sorry for my English, it is not my native language.
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();
}
});
}
}
The error is from the Client Side(Android) not from the Server Side(Windows) and is different from other questions asked in Stack overflow. This error is thrown when the App is closed from the Task, the Service keeps running and the socket is implemented inside the Service the too the comes when closing the activity and not Service.