gpt4 book ai didi

android - 如何防止应用超时?

转载 作者:太空狗 更新时间:2023-10-29 13:43:58 26 4
gpt4 key购买 nike

我已经创建了一个多线程应用程序,但如果服务器不可用,它仍然会挂起。

在主 Activity 中,我创建了以下方法:

@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 服务在它自己的线程中执行,我不知道为什么这会影响主要 Activity 的超时。

如果有人能展示如何防止应用程序在服务器不可用时挂起,我将不胜感激。

最佳答案

Android 平台始终在主事件线程中为 Activity 和服务运行生命周期方法。所以你创建了另一个线程,并从它调用 startService ......但是当服务被创建并启动时, onCreate() 等方法是从主事件线程调用的,而不是从你的用户线程。

这样做的正确方法不是从另一个线程调用 startService,而是正常调用 startService,然后让服务从 onCreate() 中生成一个连接线程。

恐怕 ssakl 的解决方案没有解决基本问题。

关于android - 如何防止应用超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/652888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com