网络监听器Android的例子 [英] Internet listener Android example

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

问题描述

你好我工作的安卓应用程序,将继续保持与互联网连接。如果把互联网下来,它应该为用户提供适当的信息。 有没有像互联网侦听器的任何事情吗?或如何实现此事件,当曾经的互联网连接不可用它应该给警报。

Hi i am working on android app that will continuously remains connected with Internet. If Internet Is down that it should give appropriate message to User. Is there any thing like Internet Listener ? or how to Implement this Event that when ever 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");
     }
   }
}

将这个code在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"/>

修改

这code只是检测连接的变化,但无法判断网络是连接到具有互联网接入。使用此方法来检查 -

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天全站免登陆