我正在开发一个Android应用程序,我想检查自上次该设备连接到互联网以来是否超过10天。我已经注册了一个网络更改接收器,以便我获得连接更改,但我不知道如何检查自上次以来它已经过了多少天。这是我的网络变更代码
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;
}
}
}
答案 0 :(得分:2)
您可以在应用的最后一次互联网连接上添加时间戳,并检查它是否已超过10天。
mSharedPrefs = context.getSharedPreferences("preferences_filename", Context.MODE_PRIVATE);
mSharedPrefs .putLong("timestamp", System.currentTimeMillis()).apply();
并使用以下方式检查:
TEN_DAYS = 10 * 24 * 60 * 60 * 1000;
System.currentTimeMillis() - sharedPrefsValue > TEN_DAYS;
答案 1 :(得分:0)
设置闹钟。 Android AlarmManager
由系统处理。创建Service
并使用服务意图制作PendingIntent
。使用PendingIntent
来触发警报。
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");
}
触发警报管理器后,您的Service
将会启动。你可以用5分钟的拍摄时间限制来检查它。
检查Scheduling Repeating Alarms了解详情。