java - Android - 通过 ping url 地址检查互联网连接
问题描述
我需要在后台不断 ping 谷歌的服务。但我不知道该怎么做。我刚来这地方。我的方法不行就不重复了。它只工作一次,并且总是返回 "false" 。
isConnectedToServer 函数
public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
// Handle your exceptions
return false;
}}
创建
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isConnectedToServer("http://www.google.com",3000)){
Toast.makeText(this, "Okay", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Not Okay", Toast.LENGTH_SHORT).show();
}}
显现
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
我在屏幕上看到一次 Not Okay。只有一次。即使我有互联网连接。我能做些什么呢?
解决方案
试试这个创建一个扩展 AsyncTask 的类
public class CheckInternet extends AsyncTask<Void, Void, Boolean>{
private static final String TAG = "CheckInternet";
private Context context;
public CheckInternet(Context context) {
this.context = context;
}
@Override
protected Boolean doInBackground(Void... voids) {
Log.d(TAG, "doInBackground: ");
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (isConnected) {
if ( executeCommand()) return true;
}
return false;
}
private boolean executeCommand(){
System.out.println("executeCommand");
Runtime runtime = Runtime.getRuntime();
try
{
Process mIpAddrProcess = runtime.exec("/system/bin/ping -c "+"www.google.com");
int mExitValue = mIpAddrProcess.waitFor();
System.out.println(" mExitValue "+mExitValue);
if(mExitValue==0){
return true;
}else{
return false;
}
}
catch (InterruptedException ignore)
{
ignore.printStackTrace();
System.out.println(" Exception:"+ignore);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println(" Exception:"+e);
}
return false;
}
推荐阅读
- python - 我收到一个错误,因为“失败:AttributeError:'ServicePrincipalCredentials'对象没有属性'get_token”
- r - 错误:编织时找不到函数“read_sav”
- c# - 使用 C# 从 Microsoft.GroupPolicy.GPTrustee 获取名称/Sid
- typescript - 使用类名来定义类型中的属性
- sql - 尝试在两个过滤表之间执行 SQL 连接
- node.js - MulterS3 - 检查请求对象的控制流
- python - QT/QML 数据模型
- html - 你能帮我在 jquery 中按价格排序吗
- json - 如何将json字符串转换回Angular 8中的对象
- angular - 以角度提供侧面渲染在所有页面中都不起作用 sping boot 后端