Created
July 11, 2024 18:28
-
-
Save cristiancorreau/3b9023e729369abf05a8428e84392e88 to your computer and use it in GitHub Desktop.
ExecutorService para manejar tareas asíncronas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.Bundle; | |
import android.widget.TextView; | |
import androidx.appcompat.app.AppCompatActivity; | |
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
import java.io.OutputStream; | |
import java.net.Socket; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
public class ExampleActivity extends AppCompatActivity { | |
private TextView textView; | |
private ExecutorService executorService; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
textView = findViewById(R.id.textView); | |
// Inicializar ExecutorService | |
executorService = Executors.newSingleThreadExecutor(); | |
// Ejecutar tarea asíncrona para conectar via socket | |
executorService.execute(new Runnable() { | |
@Override | |
public void run() { | |
// Realiza la tarea de conexión de socket en el hilo de fondo | |
final String result = connectToServer(); | |
// Actualiza la UI con el resultado | |
runOnUiThread(new Runnable() { | |
@Override | |
public void run() { | |
updateUI(result); | |
} | |
}); | |
} | |
}); | |
} | |
private String connectToServer() { | |
String serverIp = "172.172.172.172"; | |
int serverPort = 1234; // Asegúrate de que el puerto sea correcto | |
String messageToSend = "Hello, Server!"; | |
StringBuilder response = new StringBuilder(); | |
try (Socket socket = new Socket(serverIp, serverPort); | |
OutputStream outputStream = socket.getOutputStream(); | |
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { | |
// Enviar mensaje al servidor | |
outputStream.write(messageToSend.getBytes()); | |
outputStream.flush(); | |
// Leer la respuesta del servidor | |
String line; | |
while ((line = reader.readLine()) != null) { | |
response.append(line).append('\n'); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return "Error: " + e.getMessage(); | |
} | |
return response.toString(); | |
} | |
private void updateUI(String result) { | |
textView.setText(result); | |
} | |
@Override | |
protected void onDestroy() { | |
super.onDestroy(); | |
executorService.shutdown(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment