开发者

Creation of Socket instance blocks thread for random time if no connection available

Trying to open socket connection in separate thread by calling this:

Socket sc = sc = new Socket(address, Integer. parseInt(port));

But there is a problem, if there is no active internet connection this thread is blocking, on my htc hero 2.1 for 30 seconds, 开发者_运维百科and my android emulator 2.2 for 2 minutes.

I tryed to use this method before opening connection:

public static boolean isOnline()
{
             ConnectivityManager cm = (ConnectivityManager) app.getInstance().getSystemService(Context. CONNECTIVITY_SERVICE);
             if(null != cm.getActiveNetworkInfo())
                   return cm.getActiveNetworkInfo().isConnectedOrConnecting();
             return false ;
}


public void run()
{
    if(!isOnline())
        throw new IOException("internet not connected");
    Socket sc = new Socket(address, Integer. parseInt(port));
}

And everything is good, But if active connection will lost after isOnline was called, and before new Socket call, its still blocks for random time.

My question is there any possibility to solve that problem? or just block this thread for fixed time for about 2-3 seconds?


I suggest calling thread.interrupt() after a timeout.

You might also want to get the Android source and see where it's spending all that time. It might give you some insight on other approaches to dealing with this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜