Android - Socket Write AsyncTask Timeout

I have a background alarm that fires every minute using the example given here:

Alarm Manager Example

My actual alarm fires AsyncTask (as I am doing a network transaction), which looks like this:

Socket sock = new Socket("hostname.com", 1234);
        OutputStream out = sock.getOutputStream();
        String data = "beth";
        out.write(data.getBytes());
        sock.close();

What is the easiest way to make this timeout in case of an unstable network connection? I am already checking if the phone is connected to Wi-Fi.

setSoTimeout is similar to what I want to use, but it is only for sockets that receive content. I want the connection to end after a few seconds if it fails to connect.

In response to the first comment:

Before I run:

new Checkin().execute();

Now I run:

new Checkin().get(10000, TimeUnit.MILLISECONDS);

Timeout in 10 seconds? And it will stop asyncascus in 10 seconds?

+3
1

connect()

Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 10000);
0

All Articles