我创建了一个多线程应用程序,但如果服务器不可用,它仍然会挂起。
在主活动中,我创建了以下方法:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//bind GUI elements
...
//start TCPConnection Service in a new thread
establishTCPConnection();
...
}
private void establishTCPConnection(){
TCPClientServiceThread = new Thread(null, backgroundConnection, "connection");
TCPClientServiceThread.start();
}
..
private Runnable backgroundConnection = new Runnable(){
public void run(){
//establish TCP connection
doEstablishTCPConnection();
}
};
private void doEstablishTCPConnection()
{
//start TCPConnection service
startService(new Intent(this, TCPClientService.class));
}
这是 TCPClientService 类:
public class TCPClientService extends Service{
...
private String serverAddress = "192.168.1.5";
private int portNumber = 1000;
@Override
public void onCreate()
{
//TODO: Actions to perform when service is created
connectionAvailable = false;
IntentFilter dataReceiverFilter;
dataReceiverFilter = new IntentFilter(MotranetClient.MOTION_DATA_UPDATED);
dataReceiver = new DataReceiver();
registerReceiver(dataReceiver, dataReceiverFilter);
EstablishConnection();
}
@Override
public IBinder onBind(Intent intent)
{
//TODO: Replace with service binding implementation
return null;
}
private void EstablishConnection()
{
try {
InetAddress serverAddr = InetAddress.getByName(serverAddress);
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, portNumber);
String message = "testing connection";
try {
Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println(message);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
connectionAvailable = true;
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
connectionAvailable = false;
} finally {
socket.close();
announceNetworkAvailability(connectionAvailable);
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
announceNetworkAvailability(connectionAvailable);
}
}
}
当服务器不可用时,线路
Socket socket = new Socket(serverAddr, portNumber);
导致一些延迟,我相信这是挂起的原因。但是如果 TCPClientService 服务在自己的线程中执行,我不知道为什么这会影响主要活动的超时。
如果有人能展示如何防止应用程序在服务器不可用时挂起,我将非常感激。