如何在应用程序启动前和运行时检查互联网连接?

时间:2016-05-25 07:41:35

标签: android

我找到了很多关于此的答案,但也无法实现。 我想在这里实现这个代码但不能这样做。

我在google文档中找到了这段代码。

ConnectivityManager cm =
           (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

  NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
  boolean isConnected = activeNetwork != null &&
                  activeNetwork.isConnectedOrConnecting();   

https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html#DetermineConnection

public class JSONfunctions {

public static JSONObject getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // Convert response to string
    try {
        BufferedReader reader = null;
        if (is != null) {
            reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
        }
        StringBuilder sb = new StringBuilder();
        String line;
        if (reader != null) {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        }
        if (is != null) {
            is.close();
        }
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}

}

5 个答案:

答案 0 :(得分:0)

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null) {
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
            return true;
        }
    }
    return false;
}

答案 1 :(得分:0)

检查互联网连接的简单功能

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

并在AndroidManifest.xml中添加权限

 public ActionResult Index()
        {
            DataTable dt = GetData();

            return View(dt);
        }

答案 2 :(得分:0)

{{1}}

答案 3 :(得分:0)

像这样,您可以在项目的公共文件中创建此方法

 public static boolean isNetworkAvailable(Context ctx) {
    ConnectivityManager cm = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        return false;
    }
}

并使用

if(commonfile.isNetworkAvilable(pass your context here))
{
  //call your method
}

并且不要忘记在您的演示文稿中添加Internet权限

答案 4 :(得分:0)

如果您的设备连接到互联网但没有输入数据,会发生什么?您还必须检查是否正在接收数据。检查以下代码,看看您是否已连接互联网并能够访问数据。您只需要ping一个站点,看看你的回复是否为200。

 public class internetchek extends AsyncTask<Void,Void,Void> {

 public boolean connection;
 Context ctx;
 public internetchek(Context context){
  this.ctx = context;
 }
 public internetchek(){

 }
@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected Void doInBackground(Void... params) {

if(isNetworkAvailable(this.ctx))
{

 Log.d("NetworkAvailable","TRUE");
    if(connectGoogle())
    {

        Log.d("GooglePing","TRUE");
        connection=true;
    }
    else
    {

        Log.d("GooglePing","FALSE");
        connection=false;
    }
 }
 else {

    connection=false;
 }


 return null;
 }

 @Override
 protected void onPostExecute(Void aVoid) {
   super.onPostExecute(aVoid);
 }

 public static boolean isNetworkAvailable(Context context) {
   ConnectivityManager cm = (ConnectivityManager)        context.getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo netInfo = cm.getActiveNetworkInfo();
   if (netInfo != null && netInfo.isConnected()) {
    return true;
   }
   return false;
  }

  public static boolean connectGoogle() {
    try {
     HttpURLConnection urlc = (HttpURLConnection) (new     URL("http://www.google.com").openConnection());
    urlc.setRequestProperty("User-Agent", "Test");
    urlc.setRequestProperty("Connection", "close");
    urlc.setConnectTimeout(10000);
    urlc.connect();
    return (urlc.getResponseCode() == 200);

  } catch (IOException e) {

     Log.d("GooglePing","IOEXCEPTION");
     e.printStackTrace();
     return false;
  }
} 

更新:如果你想将它用于其他类,你可以这样做。确保你把下面的代码放在AsyncTask或后台运行的线程中。

       if(internetchek.isNetworkAvailable(this.ctx)||internetchek.connectGoogle())
 {

 //Do your stuff here. when you have internet access 

 }