6

在我的应用程序中,如果连接了网络更改,我需要重新启动服务。目前它只能以一种方式工作(wifi 到移动数据),但它不能以另一种方式工作(移动数据到 wifi。)这是为什么?是因为我没有进入android.net.wifi.WIFI_STATE_CHANGED我的广播接收器还是许可放错了地方?

谢谢你的帮助。

代码:接收方的清单条目:

<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>

接收器本身:

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;
}

我列出的相关权限:

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

再次谢谢你!

4

1 回答 1

13

android.net.wifi.WIFI_STATE_CHANGED仅在启用或禁用 WiFi 时发送。android.net.wifi.STATE_CHANGE如果您想在连接到 WiFi 网络或从 WiFi 网络断开连接时接收广播事件,您也需要捕获。

于 2013-07-29T20:57:45.623 回答