互联网侦听器 Android 示例 [英] Internet listener Android example

查看:24
本文介绍了互联网侦听器 Android 示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个可以持续连接到互联网的 Android 应用.如果互联网是陶氏,它应该给用户适当的信息.

I am working on an Android app that will continuously remain connected to Internet. If Internet is dow, it should give an appropriate message to the User.

有没有像 Internet Listener 这样的东西?或者如何实现这个事件,当互联网连接不可用时,它应该发出警报.

Is there any thing like Internet Listener? Or how to implement this event that whenever Internet connection is not available it should give alert.

推荐答案

为此创建一个广播接收器并将其注册到清单文件中.

Create one Broadcast Receiver for that and register it in manifest file.

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

First create a new class NetworkStateReceiver and extend 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");
     }
   }
}

将此代码放在应用程序"元素下的 AndroidManifest.xml 中:

Put this code in your AndroidManifest.xml under the "application" element:

<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"/>

编辑

此代码仅检测连接更改,但无法判断其连接的网络是否可以访问互联网.用这个方法检查一下 -

This code just detects connectivity change but cannot tell whether the network it is connected to has a internet access. Use this method to check that -

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

这篇关于互联网侦听器 Android 示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆