获得有关Android设备上WiFi状态变化的通知?

时间:2017-01-22 17:30:34

标签: android wifi

我的目标是建立一个Android应用程序,记录设备WiFi适配器正在发生的一切。例如,WiFi打开/关闭,设备连接/移出WiFi路由器的范围等。 我的应用程序应该能够在设备打开后立即记录这些事件。从RECENTS清除应用程序不应影响应用程序记录这些事件的能力。 我通过了BroadcastReceiver。它与应用程序的生命周期相关联,因此一旦应用程序从RECENTS中清除,它就不会记录事件。

public class MainActivity extends Activity {
    BroadcastReceiver mybroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mybroadcastReceiver = new WifiBroadcastReceiver(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        registerReceiver(mybroadcastReceiver, intentFilter);
  }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mybroadcastReceiver);
    }
}

public class WifiBroadcastReceiver extends BroadcastReceiver {
    final String TAG = "WifiBroadcastReceiver";
    final String desiredMacAddress = "02:17:1c:96:42:fa";
    Activity activity;

    WifiBroadcastReceiver(Activity activity) {
        this.activity = activity;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
            SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);

            if (SupplicantState.isValidState(state) && state == SupplicantState.COMPLETED) 
                checkConnectedToDesiredWifi();
        }
    }

    /** Detect you are connected to a specific network. */
    private void checkConnectedToDesiredWifi() {
        WifiManager myWifiManager = (WifiManager)activity.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = myWifiManager.getConnectionInfo();

        if (wifiInfo != null) {
            // get current router MAC address
            String bssid = wifiInfo.getBSSID();

            if (desiredMacAddress.equals(bssid))
                Log.d(TAG, "Connected to " + bssid + " i.e., desiredMacAddress");
            else
                Log.d(TAG, "Connected to " + bssid + " not " + desiredMacAddress); 
        }
    }
}

1 个答案:

答案 0 :(得分:0)

一种解决方案可能是从不依赖于任何活动生命周期的服务运行BroadcastReceiver。

1)在清单

中声明网络状态权限使用
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

1)创建服务类

public class WifiService extends Service {

    private BroadcastReceiver mReceiver;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // When creating the service, register a broadcast receiver
        // to listen for network state changes
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        mReceiver = new WifiReceiver();
        registerReceiver(mReceiver, filter);
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // Unregister the receiver when unbinding the service
        unregisterReceiver(mReceiver);
        mReceiver = null;
        return super.onUnbind(intent);
    }
}

2)创建BroadcastReceiver

public class WifiReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();

        boolean isConnected = networkInfo != null &&
                              networkInfo.isConnectedOrConnecting();

        if (isConnected) {
            switch (networkInfo.getType()) {
                case ConnectivityManager.TYPE_WIFI:
                    // Connected via wifi
                    checkConnectedToDesiredWifi();
                    break;

                case ConnectivityManager.TYPE_ETHERNET:
                    // Connected via ethernet
                    break;

                case ConnectivityManager.TYPE_MOBILE:
                    // Connected via mobile data
                    break;
            }
        }
    }

    private void checkConnectedToDesiredWifi() {
        // ...
    }
}

3)在清单

中声明服务
    <service android:name=".receivers.WifiService"
             android:stopWithTask="false"
             android:enabled="true"/>