Android中响应网络变化的事件
分类:Android, Java
阅读 (2,568)
Add comments
7月 112015
1. 在AndroidManifest.xml中加入以下权限
1 |
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> |
2. 注册网络变化监听事件,在AndroidManifest.xml中加入以下代码
1 2 3 4 5 6 7 |
<receiver android:name="com.jeoe.myapp.NetworkChangeReceiver" android:label="NetworkConnection" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> |
android:name的值为NetworkChangeReceiver为类名
3,实现NetworkChangerReceiver类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { MyLog.i("NetworkChangeReceiver", "onReceive()..."); ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null) { MyLog.i("NetworkChangeReceiver", "Network Type: " + networkInfo.getTypeName()); MyLog.i("NetworkChangeReceiver", "Network State: " + networkInfo.getState()); if (networkInfo.isConnected()) { MyLog.i("NetworkChangeReceiver", "Network is connected."); } } else { MyLog.i("NetworkChangeReceiver", "Network is disconnected."); } } } |