Android P监听WIFI 状态的变化

1.需求:

需要监听WIFI的的连接状态,之前在网上搜的一些老资料发现不能实现,获取的状态不够准确。故自己写个备份。

package com.example.user.networkchangelistener;

import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.util.Log;


public class MainActivity extends AppCompatActivity {
    NetworkConnectChangedReceiver networkConnectChangedReceiver = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        networkConnectChangedReceiver = new NetworkConnectChangedReceiver();
        registerReceiver(networkConnectChangedReceiver, filter);
    }


    class NetworkConnectChangedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == WifiManager.NETWORK_STATE_CHANGED_ACTION) {
                NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (networkInfo != null) {
                    boolean isWifiConnected = networkInfo.isConnected();
                    if(isWifiConnected){
                        Log.i("MainActivity","WIFI is connected");
                        //do something
                    } else {
                        Log.i("MainActivity","WIFI is disconnected");
                        //do another thing
                    }
                }
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(networkConnectChangedReceiver);
    }
}

权限声明上面,我在我的demo里面没有加入也能监听到网络的变化,不过为了以防万一你们还是加上的好

    
    
    

 

你可能感兴趣的:(Android,学习)