java - 使用 ThreadPoolExecutor 检查服务器端口是否打开时,Android 应用程序挂起并显示黑屏 5-6 秒

标签 java android sockets executorservice threadpoolexecutor

如果服务器端口打开,我需要运行服务。我正在使用以下方法执行此操作。

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 上找到了以下消息。

W/ActivityManager: Launch timeout has expired, giving up wake lock!

服务启动后,应用程序运行良好。我怎样才能摆脱这个问题? 提前致谢。

最佳答案

经过一番研究,据我了解,

Android 应用程序挂起并显示黑屏 5-6 秒 因为,

future -

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

所以,它一直等到操作完成。您可以获得更多信息 from here.

新固定线程池 -

At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available.

获取更多信息 from here.

您的问题的可能解决方案是使用 ScheduledExecutorService.

在此之前,您可以使用

检查 Future 是否已完成

if (YOUR_FUTURE.isDone()){ 结果 = (字符串) YOUR_FUTURE.get(); }

避免不必要的或额外的循环。

关于java - 使用 ThreadPoolExecutor 检查服务器端口是否打开时,Android 应用程序挂起并显示黑屏 5-6 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44352674/

相关文章:

java - 如何在dos下编译并运行包含weka库的java文件?

Android:onMeasure() 问题

java - 通过套接字连接进行通信 :

java - Arraylist 正在将先前添加的元素与新添加的元素一起打印

java - 实现 Android 手势识别工具框架,在生成的构建文件中接收错误

android - 升级到 Android 8.1 后 startForeground 失败

android - Google Places API 不会通过 Android 中的照片引用返回照片

java - 使用 Mockito 模拟服务器-客户端连接

c# - TCP 服务器/客户端的自定义消息框架协议(protocol)

java - 如何在java中弯曲图像