检查android中的互联网连接

时间:2015-10-18 11:46:47

标签: android connection android-wifi connectivity android-internet

我正在尝试检查接收短信的互联网连接。 但我的服务是在改变互联网状态时强制关闭。例如,如果我启用了wifi工作正常但是当我禁用wifi应用程序时会因错误而关闭。 我在onReceive函数中使用此代码。 这是代码。

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

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

     if(isConnected == true) { 
            Toast.makeText(context, "Internet", Toast.LENGTH_LONG).show();
     }
     else if(isConnected == false){
            Toast.makeText(context, "No Internet", Toast.LENGTH_LONG).show();
     }    

4 个答案:

答案 0 :(得分:3)

尝试使用此代码

在清单文件中添加权限

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


public class ConnectionDetector {
public static boolean isConnectingToInternet(Context context){
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) 
    {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) 
            for (int i = 0; i < info.length; i++) 
                if (info[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    return true;
                }

    }
    return false;
 }
}

呼叫

  ConnectionDetector.isConnectingToInternet(LoginActivity.this);

答案 1 :(得分:0)

尝试使用此代码

    WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(status);

   Also add Permission in Manifest File :
   <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

答案 2 :(得分:0)

您可以添加以下

 <!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />

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

<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

请检查此演示

  1. Android Detect Internet Connection Status

答案 3 :(得分:0)

我使用此代码
创建新课程,尝试

public class Network{
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

致电

Network.isNetworkAvailable(Activity Name.this);

并使用此权限

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