Search code examples
androidconnectionperiodic-task

Check when a device last time connected to the internet


I am working on an android app and I want to check if it has been more than 10 days since last time that device was connected to the internet. I have registered a Network change receiver so that I get the connectivity changes but I have no idea how to check how many days it has been since last time. Here is my code for network changes

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetwaorkChangeReceiver();
this.registerReceiver(receiver, filter);

public class NetworkChangeReceiver extends BroadcastReceiver {
private static boolean deviceConnected;
    private static final String LOG_TAG = NetworkChangeReceiver.class.getSimpleName();
    @Override
    public void onReceive(final Context context, final Intent intent) 
    {
        final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
        final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable() || mobile.isAvailable()) 
        {
            deviceConnected=true;
        }else{
            deviceConnected=false;
        }
    }
}               

Solution

  • You can add a timestamp on last internet connectivity for your app and check if it has passed more than 10 days.

    mSharedPrefs = context.getSharedPreferences("preferences_filename", Context.MODE_PRIVATE);
    mSharedPrefs .putLong("timestamp", System.currentTimeMillis()).apply();
    

    and check using:

    TEN_DAYS = 10 * 24 * 60 * 60 * 1000;
    System.currentTimeMillis() - sharedPrefsValue > TEN_DAYS;