问题描述
如果服务器端口已打开,我需要运行服务.我通过使用以下方法来做到这一点.
I need to run a service if a server port is open. I am doing this by using below method.
public Future<Boolean> ifPortIsOpenThenStartIridiumService(final Context context, final String device_mac, final String device_imei, final String input_mobile) {
return Executors.newFixedThreadPool(20).submit(new Callable<Boolean>() {
@Override
public Boolean call() {
try {
String SERVER_IP = "IP Address";
int SERVER_PORT = Server_port;
int DURATION = 1000;
Socket socket = new Socket();
socket.connect(new InetSocketAddress(SERVER_IP, SERVER_PORT), DURATION);
socket.close();
Log.d(TAG, "Port is Open");
runIridiumService(context, device_mac, device_imei, input_mobile);
return true;
} catch (Exception ex) {
Log.d(TAG, "Port is not Open");
CustomToast.showToast(context, "No Internet Access.", "If in flight, please switch to \"Aeroplane Mode\" and connect to the airline's Wi-Fi network.", 1);
return false;
}
}
});
}
上面的代码正在工作,但是当我运行此方法时,应用程序被挂起,并且黑屏显示5-6秒钟.我在Logcat上找到以下消息.
Above code is working but when I run this method the application is getting hanged and black screen is shown for 5-6 seconds.I found below message on Logcat.
该服务启动后,应用程序运行正常.我如何摆脱这个问题?预先感谢.
After that service is started and application is working well. How can I get rid of this problem?Thanks in advance.
推荐答案
经过研究,据我了解,
Android应用程序已挂起,并在5-6秒钟内显示黑屏,因为
未来-
因此,它等待直到操作完成.您可以从这里获得更多信息.
So, it waits until operation is finished. You can get more info from here.
newFixedThreadPool -
从此处获取更多信息.
您的问题的可能解决方案是使用 ScheduledExecutorService.
The possible solution of your problem is to use ScheduledExecutorService.
在使用
if (YOUR_FUTURE.isDone()){ result = (String) YOUR_FUTURE.get();}
if (YOUR_FUTURE.isDone()){ result = (String) YOUR_FUTURE.get();}
避免不必要的循环或多余的循环.
to avoid unwanted or extra loop.
这篇关于检查服务器端口是否打开或未使用ThreadPoolExecutor时,Android应用程序已挂起并显示黑屏5-6秒钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!