Checking Device has internet connection

蓝咒 提交于 2019-12-14 04:23:25

问题


I followed this Keep checking if Device has internet connection to check internet connectivity using

BroadcastReceiver, the problem is how to call this

registerReceiver(mConnReceiver, 
       new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

from main activity


回答1:


     Try this:


     if(isNetworkStatusAvialable(getApplicationContext()))
 {
 }else
 {

      public static boolean isNetworkStatusAvialable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
        if (netInfos != null)
            if (netInfos.isConnected())
                if (netInfos.isAvailable())
                    return true;
    }
    return false;

}



回答2:


You have two options

1. in your MainActivity.java

 // create object of receiver class 
 NetworkChangeReceiver mConnReceiver = new NetworkChangeReceiver();
 //register the receiver
 registerReceiver(mConnReceiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

2. In manifest file

    <receiver android:name=".NetworkChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>


来源:https://stackoverflow.com/questions/37593058/checking-device-has-internet-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!