3

I have a background alarm running every minute using the example posted here:

Alarm Manager Example

My actual alarm launches an AsyncTask (since I am doing a network transaction), that looks like this:

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

What's the easiest way to make this timeout in case the network connection is unstable? I am already checking to see if the phone is connected to wifi.

setSoTimeout looks similar to what I want to use, but it appears to be only for sockets that are receiving content. I want the connection to give up after a few seconds if it fails to connect.

In response to the first comment:

Before I was running:

new Checkin().execute();

Do I now run:

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

To timeout after 10 seconds? And this will stop the asynctask after 10 seconds?

Community
  • 1
  • 1
xur17
  • 506
  • 1
  • 8
  • 24
  • 1
    This question could be help you out: http://stackoverflow.com/questions/7882739/android-setting-a-timeout-for-an-asynctask – kmb64 Apr 12 '12 at 00:38
  • Thanks! Please see my added code above - is this the proper way to accomplish what I want? – xur17 Apr 12 '12 at 00:53
  • I tried the code I posted above, and not it isn't executing the asynctask at all - am I misunderstanding something here? – xur17 Apr 12 '12 at 01:00
  • I am currently receiving a: java.util.concurrent.TimeoutException on the second line shown above, but it shouldn't be timing out - it should take under 10 seconds easily. It's transmitting a few bytes. – xur17 Apr 12 '12 at 01:20

1 Answers1

0

Use connect() method

Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 10000);
Harshil Kulkarni
  • 411
  • 5
  • 20
  • N.B. This will allow you to set a *connection* timeout, but it will not provide a timeout for `out.write()`. I don't know which the OP was looking for, but sometimes you need the latter (or both). – LarsH Sep 06 '17 at 19:39