要实时监测Android设备与服务器的连接状态,可以使用Socket和Handler来实现。
首先,创建一个名为"NetworkUtils"的工具类,其中包含以下方法:
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
public class SocketClient {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
private Handler handler;
public SocketClient(Handler handler) {
this.handler = handler;
}
public void connectToServer() {
try {
socket = new Socket("服务器IP地址", 8080);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
// 连接成功,发送消息到UI线程
handler.sendEmptyMessage(1);
// 循环接收服务器发送的数据
String message;
while ((message = reader.readLine()) != null) {
// 接收到数据,发送消息到UI线程
Message msg = new Message();
msg.what = 2;
msg.obj = message;
handler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
// 连接异常,发送消息到UI线程
handler.sendEmptyMessage(3);
}
}
public void sendData(String data) {
writer.println(data);
}
public void disconnectFromServer() {
try {
if (socket != null) {
socket.close();
}
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class MainActivity extends AppCompatActivity {
private TextView connectionStatus;
private SocketClient socketClient;
private Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
switch (msg.what) {
case 1:
connectionStatus.setText("已连接");
break;
case 2:
String message = (String) msg.obj;
// 处理接收到的数据
break;
case 3:
connectionStatus.setText("连接异常");
break;
}
return true;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionStatus = findViewById(R.id.connection_status);
socketClient = new SocketClient(handler);
new Thread(new Runnable() {
@Override
public void run() {
// 检查网络连接状态
if (NetworkUtils.isNetworkConnected(MainActivity.this)) {
// 连接到服务器
socketClient.connectToServer();
} else {
// 网络未连接,发送消息到UI线程
handler.sendEmptyMessage(3);
}
}
}).start();
}
@Override
protected void onDestroy() {
super.onDestroy();
// 断开与服务器的连接
socketClient.disconnectFromServer();
}
}
以上就是一个简单的实时监测Android设备与服务器连接状态的实现方法。在SocketClient类中,可以根据需要添加更多的方法来发送和接收数据。在Activity中,可以根据实际情况进行数据处理和界面更新。