2013-07-29 72 views
5

在我的應用程序中,如果連接了網絡更改,我需要重新啓動服務。目前它只適用於一種方式(無線網絡到移動數據),但它不能以另一種方式工作(移動數據到無線網絡)。這是爲什麼?是因爲我的廣播接收器沒有收到android.net.wifi.WIFI_STATE_CHANGED,或者可能是錯誤的許可?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
  • 接收機 Manifest條目android.permi ssion.ACCESS_NETWORK_STATE
  • android.permission.INTERNET對

再次感謝您!

回答

12

android.net.wifi.WIFI_STATE_CHANGED僅在啓用或禁用WiFi時發送。如果您希望在連接到WiFi網絡或從WiFi網絡斷開連接時收到廣播事件,則還需要趕上android.net.wifi.STATE_CHANGE

+0

謝謝!有效! –