如何获得wifi状态更改只播放一次

时间:2015-11-30 13:36:58

标签: android android-wifi

在我的应用程序中,我想只进行一次wifi状态更改广播。然而,当wifi改变时,我多次收到广播,我该怎么办?

public class WifiChangedReceiver extends BroadcastReceiver {
public static String TAG = "WifiChangedReceiver";
@Override
public void onReceive(Context context, Intent intent) {
    ConnectivityManager connMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    boolean isConnected = wifi != null && wifi.isConnected();
    if (isConnected) {
        WifiManager wifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        String wifi_ssid = wifiManager.getConnectionInfo().getSSID();
        Log.d(TAG, "wifi  connected==="+wifi_ssid); 
    } else {
        Log.d(TAG, "wifi  disconnected"); 
    }
}


public class MainActivity extends Activity {

private WifiChangedReceiver mReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if(mReceiver==null){
        mReceiver = new WifiChangedReceiver();
    }
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    registerReceiver(mReceiver, filter);    
}

@Override
protected void onDestroy() {
    if(mReceiver!=null){
        unregisterReceiver(mReceiver);
    }
    super.onDestroy();
}

LogCat:wifi Camus到Tutu enter image description here

LogCat:wifi图图到加缪 enter image description here

2 个答案:

答案 0 :(得分:0)

首先将共享偏好中的值存储为值" off"并且在取消注册期间更改它的值。因此它不会再次注册,所以你不会再次收到广播。

PF = preferenceManager.getdefaultsharedpreferences();

pf.edit()的getString("状态&#34)。

如果(pf.getString(状态).equals("关闭&#34)) {

注册接收器

}

然后在取消注册期间

{

pf.edit()putString。("状态"" ON&#34)

取消注册接收器

}

答案 1 :(得分:0)

我通过谷歌解决了这个问题,虽然反应不是立竿见影,但它对我的项目很有用。我发布了代码,可能对其他人有用。

{{1}}