need to run service while device got wifi/data connection

白昼怎懂夜的黑 提交于 2019-12-01 11:06:38

To check the WiFi connection you can use this

ConnectivityManager connManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
// Do whatever
}

To execute the code whenever the Wifi is connected, you have to register Brodcast Recevier

Register the receiver

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);

In your Receiver class do this

@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
    if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) {
        //do stuff
    } else {
        // wifi connection was lost
    }
}

And as mentioned below, dont forget to add the permission in your AndroidManifest.xml

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