广播接收器不适用于wifi状态

时间:2016-10-03 08:03:40

标签: android broadcastreceiver

我试图通过广播接收器拦截wifi状态。这是我的代码:

manifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.gms.samples.vision.wifivision"
    android:installLocation="auto" >

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permisssion.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permisssion.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.FLASHLIGHT"/>

    <application
        android:allowBackup="true"
        android:fullBackupContent="false"
        android:hardwareAccelerated="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Wifi Vision"
        android:supportsRtl = "true"
        android:theme="@style/Theme.AppCompat" >
        <receiver android:name=".receiver.WifiReceiver" >
            <intent-filter>
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
       <!-- activity -->
    </application>
</manifest>

这里的课程:

public class WifiReceiver extends BroadcastReceiver {
    private final String TAG = "WifiReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
               int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
        String wifiStateText = "No State";

        switch (wifiState) {
            case WifiManager.WIFI_STATE_DISABLING:
                wifiStateText = "WIFI_STATE_DISABLING";
                break;
            case WifiManager.WIFI_STATE_DISABLED:
                wifiStateText = "WIFI_STATE_DISABLED";
                break;
            case WifiManager.WIFI_STATE_ENABLING:
                wifiStateText = "WIFI_STATE_ENABLING";
                break;
            case WifiManager.WIFI_STATE_ENABLED:
                wifiStateText = "WIFI_STATE_ENABLED";
                break;
            case WifiManager.WIFI_STATE_UNKNOWN:
                wifiStateText = "WIFI_STATE_UNKNOWN";
                break;
            default:
                break;
        }
    }
}

我从未进入'onReceive'功能。你知道它为什么不起作用吗?

1 个答案:

答案 0 :(得分:4)

也在意图过滤器中添加

action android:name="android.net.conn.CONNECTIVITY_CHANGE"