Android 監聽網絡連接狀態的改變:
BroadcastReceiver
- public class MyReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- // TODO Auto-generated method stub
- //Toast.makeText(context, intent.getAction(), 1).show();
- ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
- NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
- NetworkInfo activeInfo = manager.getActiveNetworkInfo();
- Toast.makeText(context, "mobile:"+mobileInfo.isConnected()+"\n"+"wifi:"+wifiInfo.isConnected()
- +"\n"+"active:"+activeInfo.getTypeName(), 1).show();
- } //如果無網絡連接activeInfo為null
-
- }
在清單文件中注冊 BroadcastReceiver
- <receiver android:name=".MyReceiver">
- <intent-filter>
- <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
- </intent-filter>
- </receiver>
要讀取網絡狀態記得要加權限
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11