- package com.app.test02;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo.State;
- import android.widget.Toast;
- /**
- * Android 利用廣播BroadCast監聽網絡的變化
- * @author 402-9
- *
- */
- public class BroadCastDemo extends BroadcastReceiver{
- State wifiState = null;
- State mobileState = null;
- public static final String ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
- @Override
- public void onReceive(Context context, Intent intent) {
- // TODO Auto-generated method stub
- if (ACTION.equals(intent.getAction())) {
- //獲取手機的連接服務管理器,這裏是連接管理器類
- ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
- wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
- mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
- Intent intent2 = new Intent(context , BroadCastActivity2_SMS.class);
- if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED == mobileState) {
- context.startService(intent2);
- Toast.makeText(context, "手機網絡連接成功!", Toast.LENGTH_SHORT).show();
- } else if (wifiState != null && mobileState != null && State.CONNECTED == wifiState && State.CONNECTED != mobileState) {
- context.startService(intent2);
- Toast.makeText(context, "無線網絡連接成功!", Toast.LENGTH_SHORT).show();
- } else if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED != mobileState) {
- context.startService(intent2);
- Toast.makeText(context, "手機沒有任何網絡...", Toast.LENGTH_SHORT).show();
- }
- }
- }
- }
增加權限
- <receiver android:name=".BroadCastDemo">
- <intent-filter >
- <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
- </intent-filter>
- </receiver>
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
效果圖