Browse Source

connectToWifi in Future

master
Tim Zeuner 1 year ago
parent
commit
ffb38996e8
1 changed files with 32 additions and 15 deletions
  1. 32
    15
      MobileApp/app/src/main/java/com/example/lfrmobileapp/MainActivity.java

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

@@ -17,13 +17,17 @@ import com.example.lfrmobileapp.databinding.ActivityMainBinding;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
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 {

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

@@ -46,21 +50,29 @@ public class MainActivity extends AppCompatActivity {
}

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){
dataTransferAsyncTask = new DataTransferAsyncTask(socket);
@@ -70,5 +82,10 @@ public class MainActivity extends AppCompatActivity {
return false;
}
}

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


Loading…
Cancel
Save