android.net.wifi.WIFI_STATE_CHANGED not being broadcast

只愿长相守 提交于 2020-01-01 09:52:56

问题


In my app, I need a service restarted if a network change is connected. Currently it only works one way (wifi to mobile data) but it doesn't work the other way (mobile data to wifi.) Why is this? Is it because I'm not getting android.net.wifi.WIFI_STATE_CHANGED in my broadcast receiver or maybe a misplaced permission?

Thanks for any help.

Code: Manifest entry for receiver:

<receiver
    android:name="LiveForever"
    android:label="NetworkChangeReceiver" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
    </intent-filter>
</receiver>

The receiver itself:

public static final int TYPE_WIFI = 1;
public static final int TYPE_MOBILE = 2;
public static final int TYPE_NOT_CONNECTED = 0;
public static final String PREFS_NAME = "cakecloudpreferences";

@Override
public void onReceive(Context context, Intent intent) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
    if (getConnectivityStatus(context)!=0&&!settings.getBoolean("osmframerunning",false)) {
        context.stopService(new Intent(context, OSMFrame.class));
        settings.edit().putBoolean("osmframerunning",false).commit();
        Intent frameintent = new Intent(context,OSMFrame.class);
        frameintent.putExtra("username",settings.getString("usr",""));
        frameintent.putExtra("password",settings.getString("pswd",""));
        frameintent.putExtra("uid",settings.getString("uid",""));
        context.startService(frameintent);
        Log.i("CCLiveForever","LiveForever Triggered, OSMFrame restarted.");
    }
}

public int getConnectivityStatus(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (null != activeNetwork) {
        if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) return TYPE_WIFI;
        if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) return TYPE_MOBILE;
    } 
    return TYPE_NOT_CONNECTED;
}

Relevant permissions I have listed:

  • android.permission.ACCESS_WIFI_STATE
  • android.permission.ACCESS_NETWORK_STATE
  • android.permission.INTERNET

Again, thank you!


回答1:


android.net.wifi.WIFI_STATE_CHANGED is sent only when WiFi is enabled or disabled. You need to catch android.net.wifi.STATE_CHANGE too if you want to receive broadcast event when you are connected to or disconnected from a WiFi network.



来源:https://stackoverflow.com/questions/17929086/android-net-wifi-wifi-state-changed-not-being-broadcast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!