如何在MainActivity中,ping需要的IP地址,降丢包率信息显示在 TextView 中
时间: 2023-05-21 10:01:08 浏览: 119
您可以使用以下代码在 MainActivity 中 ping 指定的 IP 地址,并将丢包率信息显示在 TextView 中:
```
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.text_view);
String ipAddress = "192.168.1.1"; // 指定的 IP 地址
try {
Process process = Runtime.getRuntime().exec("/system/bin/ping -c 4 " + ipAddress);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int packetsSent = 0;
int packetsReceived = 0;
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("packets transmitted")) {
packetsSent = Integer.parseInt(line.split(" ")[0]);
} else if (line.contains("packets received")) {
packetsReceived = Integer.parseInt(line.split(" ")[0]);
} else if (line.contains("packet loss")) {
String[] parts = line.split(", ");
String packetLoss = parts[2].split("%")[0];
mTextView.setText("丢包率:" + packetLoss + "%");
}
}
reader.close();
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请注意,您需要在 AndroidManifest.xml 文件中添加以下权限:
```
<uses-permission android:name="android.permission.INTERNET" />
```
阅读全文