Browse Source

connectToWifi in Future

master
Tim Zeuner 1 year ago
parent
commit
ffb38996e8

+ 32
- 15
MobileApp/app/src/main/java/com/example/lfrmobileapp/MainActivity.java View File



import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket; import java.net.Socket;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {


private ActivityMainBinding binding; private ActivityMainBinding binding;
private ExtendedSocket socket; private ExtendedSocket socket;
private DataOutputStream outputStream;
private DataTransferAsyncTask dataTransferAsyncTask; private DataTransferAsyncTask dataTransferAsyncTask;
Boolean connected = false; Boolean connected = false;


} }


public boolean connectToWifi(String ipAddress, int port){ public boolean connectToWifi(String ipAddress, int port){

new Thread(new Runnable(){
public void run(){
try {
Socket tempSocket = new Socket(ipAddress, port);
socket = new ExtendedSocket(tempSocket);
socket.sendMessage("Verbindung aufbauen");
connected = true;

} catch (Exception e) {
e.printStackTrace();
connected = false;
}
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Boolean> future = executor.submit(() -> {
Socket tempSocket = new Socket();
tempSocket.connect(new InetSocketAddress(ipAddress, port), 1000);
try {
socket = new ExtendedSocket(tempSocket);
socket.sendMessage("Verbindung aufbauen");
} catch (Exception e) {
socket.closeSocket();
return false;
} }
}).start();
return true;
});

try {
connected = future.get();
} catch (InterruptedException e) {
System.err.println("InterruptedException: " + e.getMessage());
} catch (ExecutionException e) {
System.err.println("ExecutionException: " + e.getCause().getMessage());
}

executor.shutdown();


if(connected){ if(connected){
dataTransferAsyncTask = new DataTransferAsyncTask(socket); dataTransferAsyncTask = new DataTransferAsyncTask(socket);
return false; return false;
} }
} }

public void sendTelegram(String telegram)
{
this.dataTransferAsyncTask.writeTelegram(telegram);
}
} }



Loading…
Cancel
Save