网络丢失时通知

时间:2012-08-16 07:40:18

标签: android broadcastreceiver

如何判断设备上的网络状态何时发生变化?

我需要什么权限?

1 个答案:

答案 0 :(得分:3)

您应该创建一个在连接状态发生变化时将被触发的BroadcastReceiver

   public class InternetConnectionChangeReceiver extends BroadcastReceiver 
   {
            public void onReceive(Context context, Intent intent) {
                boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
                String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
                boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

                NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

                if(currentNetworkInfo.isConnected()){
                    Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
                }
            }
        }

在清单文件中添加以下权限。

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

在清单文件中注册您的广播接收器。

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