简体   繁体   中英

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;
        }
    }
}               

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;

Set a alarm. Android AlarmManager is handled by system. Create a Service and make a PendingIntent with the service intent. Use that PendingIntent to trigger your alarm.

 private void setAlarmForTenDays(Context context) {
     PendingIntent pendingIntentAutoBackupService = PendingIntent.getService(context,0,new Intent(context, MyService.class),0);
     AlarmManager manager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
     //long interval = 1000*60*60*24*10;
      long interval = AlarmManager.INTERVAL_DAY*10;
     manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntentAutoBackupService);
    Log.d("Alarm", " Alarm created");

}

When your alarm manager is triggered your Service will be started. You can check it with shot time limit like 5 min.

Check Scheduling Repeating Alarms to learn more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM