在清单中声明的​​android – BroadcastReceiver不接收广播

前端之家收集整理的这篇文章主要介绍了在清单中声明的​​android – BroadcastReceiver不接收广播前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我尝试注册一个Wifi BroadcastReceiver以获取WiFi状态,当它改变.但到目前为止,我没有收到广播的运气.
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <receiver android:name=".WifiReceiver" >
        <intent-filter>
            <action android:name="android.net.wifi.WifiManager.WIFI_STATE_CHANGED_ACTION" />
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
    </receiver>

    //activity declaration here...

</application>

你们知道如何在清单中注册BraodcastReceiver?

我不想在活动中注册,因为当WiFi状态发生变化时,我想监控wifi,无论我的应用程序是否正在运行.

这是我的BroadcastReceiver类:

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;
        }
        MyLog.d(TAG,"onReceive Broadcast > WiFiState: " + wifiStateText);
        MyLog.d(TAG,"onReceive Broadcast > Time: " + new Date());
    }
}

我真的希望得到一些帮助.提前致谢.

解决方法

清单中的接收者应该看起来像这样
<receiver android:name=".WifiReceiver" >
    <intent-filter>
       <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
    </intent-filter>
</receiver>

还可能需要以下许可

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
原文链接:https://www.f2er.com/android/313128.html

猜你在找的Android相关文章