简体   繁体   English

Android - 通过 ping url 地址检查互联网连接

[英]Android - Check internet connection by pinging url address

I need a service in the background that constantly pings google.我需要在后台不断地 ping 谷歌的服务。 But I have no idea how to do it.但我不知道该怎么做。 I am new here.我刚来这地方。 My method does not work does not repeat.我的方法不行就不重复了。 It only works once and it always returns "false" .它只工作一次,它总是返回 "false" 。

isConnectedToServer function 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;
}}

onCreate在创建

     @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();
    }}

Manifest显现

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

I see Not Okay once on the screen.我在屏幕上看到 Not Okay 一次。 Only once.只有一次。 Even when I have an internet connection.即使我有互联网连接。 What can I do about it?我该怎么办?

try this create a class that extends AsyncTask试试这个创建一个扩展 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM