我正在开发一个Android应用程序,该应用程序将继续保持与Internet的连接。如果互联网是陶氏的,则应向用户提供适当的消息。

有没有像Internet Listener这样的东西?或如何实现此事件,以便每当Internet连接不可用时都应发出警报。

最佳答案

为此创建一个广播接收器,并将其注册到 list 文件中。

首先创建一个新的类NetworkStateReceiver并扩展BroadcastReceiver。

public class NetworkStateReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
     Log.d("app","Network connectivity change");
     if(intent.getExtras()!=null) {
        NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
        if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
            Log.i("app","Network "+ni.getTypeName()+" connected");
        }
     }
     if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
            Log.d("app","There's no network connectivity");
     }
   }
}

将此代码放在“application”元素下的AndroidManifest.xml中:
<receiver android:name=".NetworkStateReceiver">
   <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>

并添加此权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

编辑

该代码仅检测连接性变化,但无法判断其连接的网络是否可以访问互联网。使用此方法检查-
public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
        Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
    Log.d(LOG_TAG, "No network available!");
    }
    return false;
}

10-07 19:27
查看更多