Search code examples
androidserviceandroid-wifi

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(InitActivity.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();        
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);                
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 50 * 1000, pintent);
return getZipInfo.toString();

to make better performance, I want to run my background service once device is connect WIFI/data connection. To make clear, if device is not connect wifi/data connection, my background service will not run for sure. Once connect wifi/data connection, it will run immediately.


Solution

  • To check the WiFi connection you can use

    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 use Broadcast Receiver

    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 don't forget to add below permission in your AndroidManifest.xml

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