Android实时服务器连接状态



想知道是否可以持续监控与服务器的一些wifi连接(一些ip和端口(并显示连接状态,即服务器是否可访问/响应。

通过显示状态,我的意思是更新一些文本视图;服务器启动";或";服务器关闭";。(类似于右上角电池指示旁边的wifi图标。(

答案是创建一个线程类,它将不断调用(使用while循环(异步任务。asynctask将(尝试(连接到mysql服务器。连接将成功与否,并且相应地textview或什么将在UIthread(使用runOnUiThread(中被更新

线程的代码示例:

class servlookthread extends Thread {
@Override
public void run() {
while (keeplookingserver){
lookforserver lserv = new lookforserver(); // this is the asynctask thread
try {lserv.execute().get();} catch (ExecutionException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();} //! .get() it waits until the asynctask finishes
try {Thread.sleep(4000);} catch (InterruptedException e) {e.printStackTrace();} // some delay, 4 seconds
}
return;
}
}

keepwlookingserver是一个布尔值;全局";用于控制线程执行的变量。

希望这能帮助到别人!虽然我认为它不优雅,但它对我来说很有用

最新更新