Skip to content Skip to sidebar Skip to footer

Need To Run Service While Device Got Wifi/data Connection

Last time, I use following coding to run background service. Intent intent = new Intent(InitActivity.this, GetService.class); PendingIntent pintent = PendingIntent.getService(InitA

Solution 1:

To check the WiFi connection you can use

ConnectivityManagerconnManager= (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfomWifi= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

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

To execute the code whenever the Wifi is connected, you have to use Broadcast Receiver

Register the receiver

IntentFilterintentFilter=newIntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);

In your Receiver class do this

@OverridepublicvoidonReceive(Context context, Intent intent) {
finalStringaction= 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 don't forget to add below permission in your AndroidManifest.xml

<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE" />

Post a Comment for "Need To Run Service While Device Got Wifi/data Connection"