I'm downloading a certain website in html format to my device, so that I can display it in webview in offline mode. The only problem is that the link is dynamic, and it changes once a week. To keep the html item updated as much as possible, I want the app to download it once a week.
Let's say for example that this is the websites address:
www.mywebsite.com/1
Next week, the address will be:
www.mywebsite.com/2
And week after that, the website will be:
www.mywebsite.com/3
I already figured I would do this be declaring a variable that would be changing, something like
int week;
String urlToDownload = "www.mywebsite.com/" + week;
But how do I make it so that this variable will change everyday even if the app is not started, or is there a better way to do this?
You can maybe use AlarmManager class. That allows you to plan something on the background, when app is not even running.
I would use the most simple solution. Do you know what time does the URL change? You can always check the time of previous start of application and when next app is started check it and determine how many weeks is from that.
Use the java.util.Calendar
Calendar calender = Calendar.getInstance();
MyLog.d("Current Week:", "" + calender.get(Calendar.WEEK_OF_YEAR));
This prints "Current Week: 37"
With that maybe you can write code to get the appropriate page. The week nr are kind of static
You can update the variable during the onStart() phase. Make a constant that has the start date, and then get the current date and figure out the offset. This way even if the app hasnt been started in a long time, once it is started you will have the proper link.
Related
I am currently developing an app that used for write some document and send them to a database. Issue is app need to get date and time automatically when form created and users can modify system date & time.
First, I search for solution on the internet, then one of the solutions is using a service that return time and later on count that time, so time can not be modified by user. This solution will not for this app because users can be in a place that do not have cell reception or internet access, so app need to work without internet access as long as sending data to remote database via internet.(date of form must be the time when form created)
Second idea is about network-provided time and time zone. If user want to change, he or she must disable those setting then modify time. I think when user want to write a form, app will check whether it is on or off. If it is of app will show an alert dialog which force them to activate those settings.
So I tested, I turned off wifi and cellular, turned off those setting, modified time and waited for a couple minutes. Then I turned on those setting and system showed correct time.
Also, after system corrected its date and time without network connection when I activated network-provided time and time zone setting, It made me think maybe app can get date from a place that user can not modify, yet I could not find information about this.
So I am looking for reliable method, and open for new ideas. If there was not I will implement second method.
Thank all of you who spared their time and read this.
And Second solustion will look like this:
private boolean isTimeZoneAutomatic(Context c) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return Settings.Global.getInt(c.getContentResolver(), Settings.Global.AUTO_TIME_ZONE, 0) == 1;
} else {
return android.provider.Settings.System.getInt(c.getContentResolver(), Settings.System.AUTO_TIME_ZONE, 0) == 1;
}
}
Do you have any suggestion?
right now i created a project and one of the features is daily-check in.
with this I got into some difficulties.
The case is - i want the user to do daily check in.That means, after a check in, The user must wait until tomorrow to do the daily check-in again. how should i implements this and how should the validation work?
I already found the solution in google but couldn't get it to work.
I also already tested using a scheduler.
It works but i think this is not the best practice i can get here, so if someone has a solution, I'd love to hear.
I would just keep an instance of the last day the user checked in regardless the time it happened..
And so you could just check if at a particular date a check in has occurred or not.
Use -
String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
to get the current date parameter and then do the check as followed -
if(currentDate.after(lastCheckInDate)){
//your check in method here
}
Not really sure if this is the best solution, but here is how I would solve this.
Under your Users/user-id, add a field called 'lastCheckinTime'.
When the user is checking in, first call the lastCheckinTime and see if it <24hrs, if not only then let the user checkin.
Then on writing the new check-in operation, update the lastCheckinTime with the latest timestamp. Hope it answers your question.
I'm developing an android application and hit the problem with determining system first boot up time. I mean i need to measure how much time already passed from device first boot up.
I know about solution with listening for ACTION_BOOT_COMPLETED and save anything in SharedPreferences, but i need another solution, because this one does not work for some cases. Maybe there is any system property?
Use case (excerpt from discussion)
The filename of each file I receive from server includes a timestamp
taken from System.currentMillis()
I compare those timestamps in order to determine, which file the most current one is.
Now, the user changes system time a few months ahead.
I am still able to determine the most current file downloaded after user changed system time.
Now, the user changes time back to original setting.
The file downloaded on step 4 always wins when comparing timestamps.
The silver bullet to solve this problem would be a timestamp that counts seconds since first boot (after factory reset). Just like SystemClock.elapsedRealtime() but without reset after each boot. Unfortunately, the answers so far tell us, that this silver bullet doesn't exist.
However, many answers show a great variety of options how to tackle that problem. OneWorld123 commented each answer, how that suited his needs.
Maybe there is any system property?
Not sure about system property, but there is SystemClock class which provides API's to get system uptime:
SystemClock.uptimeMillis() which
Returns milliseconds since boot, not counting time spent in deep sleep.
You may also use SystemClock.elapsedRealtime() which
Returns milliseconds since boot, including time spent in sleep.
Hope this helps.
In case one needs to know when was the first time an Android device was booted,
The easiest method would be to have an application
that is installed in the factory image
that is configured to run during boot
that logs the current date & time into a sharedPreference on its first run
Subsequently any other apps that need to determine the first boot time of the Android device can lookup the appropriate sharedPreference during the lifetime of the device. (or until the device is factory-reset; at which point the pre-installed app would write the new date&time into the shared preference after a reboot.)
However if it is not possible to an pre-install an application on the Android device, then a couple of potential workarounds would be:
1. As a root/superuser
one would lookup the time-stamp of a directory/file that is known to get created on the Android device during first-boot.
2. As a regular app,
a simple workaround method using standard Android APIs would be to check for the installation-time of an appropriate system package that is known to get installed during first-boot.
/* This returns the last time a package was installed */
PackageManager pm = context.getPackageManager();
PackageInfo pInfo = pm.getPackageInfo(<app-package-name>, 0);
return pInfo.firstInstallTime;
3. Alternately as a regular app,
if we can rely on a specific package being updated one-time during first-boot (and never again) we can check its update-time as follows:
/* This returns the last time a package was updated */
PackageManager pm = context.getPackageManager();
ApplicationInfo appInfo = pm.getApplicationInfo(<app-package-name>, 0);
String appFile = appInfo.sourceDir;
long installed = new File(appFile).lastModified();
If we stick to the SDK, I don't know of a method providing this information directly; but there might be a way to derive this information from other resources. Again, if we stick to SDK, one "rather reliable" option is to use application usage statistics which Android OS saves during device lifetime. That is - the timestamp for a first "usage stats" ever saved.
This, though, clearly does not provide an exact "first boot time" timestamp, so it depends on whether some approximation is OK in your case. Generally, the problem with usage statistics is that Andriod aggregates it for periods distant in time - so, the older device is - the less accurate the date is. For example, for my current phone, first booted on Dec. 3 2014, aggregated usage statistics is first recorded on Dec. 21 2014 currently (for the record - it is Feb. 2016 by the time of this writing). (I have to admit though that I don't know how Android OS schedules the aggregation, and if it is just scheduled on Dec. 21 every year, or if it is indeed somewhat close to the first device usage - I guess it is easy to check with any other device.)
Following is some sample code showing UsageStatsManager usage, but it certainly would need more adjustments in order to address the fact of having more precision for more recent periods:
UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
Calendar year2013 = Calendar.getInstance(); year2013.set(2013, 0, 1);
List<UsageStats> stats = usageStatsManager.queryUsageStats(
UsageStatsManager.INTERVAL_YEARLY, // or adjust for "younger" devices to get more precision - so, you'll probably need several queries
year2013.getTimeMillis(),
Calendar.getInstance().getTimeInMillis());
// now, first element in stats (if it is present at all) will point to the "earliest" statistics saved *for this interval* (yearly in this case)
// use UsageStats.getFirstTimeStamp() to get first known/saved usage
Note also that, as documented in the SDK, UsageStatsManager requires PACKAGE_USAGE_STATS system-level permission, so you'll need to make user accept it in Settings first:
Intent settingsIntent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(settingsIntent);
Hope it helps!
According to your discussion on: https://chat.stackoverflow.com/rooms/102325/discussion-between-ankitagrawal-and-oneworld , you need a monotonic counter to uniquely identify a dataset.
For that you can easily set a SharedPreference and increment this value every time you need a new identifier. When you require to know which is the newest file, just compare the identifiers. If it is an issue that this counter gets reset once the app is uninstalled, please refer to: In android is there any way to preserve SharedPreferences after an uninstall
A different approach that could be used, is to request a timestamp from an outside server.
Hope it helps ;-)
There are 3 methods in ANDROID SDK for these:-
public static long elapsedRealtime ()
Added in API level 1
Returns milliseconds since boot, including time spent in sleep.
Returns
elapsed milliseconds since boot.
public static long elapsedRealtimeNanos ()
Added in API level 17
Returns nanoseconds since boot, including time spent in sleep. Returns
elapsed nanoseconds since boot.
For #oneWorld Case:
You can use 2 approach:-
1) While writing check if some data has date above the current date then change the date of previous data to something less than current data and time,
so it will return correct latest data.
2) You can store the time on server and retrieve time from there and set it.
I currently have an Android application that displays a schedule for a ferry boat. The application can display the full schedule (just a giant list), but the selling point in the application is it will display when the next two ferries are departing and how long from the current time that departure is.
I am relatively new to Java and currently use large Switch() statements in my code. Basically it gets the current phone time and compares it to all of the times in the schedule at which point it displays the next two departure times and then calculates the difference between current time and the departure times.
I am sure that a switch statement is not the best idea for speed purposes as well as code changing purposes. For example if one time changes its a bunch of lines of code to go in and fix for that one time change. Also if the entire schedule changes everyone has to update their app for the time change to take effect. My ideal situation would be to store a file somewhere on my webserver that could be downloaded and inserted into a hashmap (I think is the correct term) that would load the new schedule if there was a time change.
Not sure how confusing this is, but it would be greatly appreciated if someone could explain how I might use a hashmap or something else you might recommend to get this task accomplished. Currently the variables are the two ferry terminals as well as the day of the week since the schedule changes per day (monday, tues-friday, saturday, sunday).
Below is a screenshot of the application so you can understand it if my post wasn't clear. Thank you in advance.
Screenshot:
Store the schedule objects in a sorted array. You can then binary search the array for the first value greater than the current time. You'll probably use some parent array consisting of the location and applicable day of the week.
You can easily write that kind of data structure to a file that is read & parsed by the application for updates instead of being compiled into the code.
Details of this? First, understand resources in Android. If no updated schedule exists, fall back to the default resource.
Second, use an HTTP head request to check if a newer file exists. If it does, parse, download & save state. Saving Android Activity state using Save Instance State.
Finally, XML is handy for data distribution, even if it's not fast. Everybody understands it and it's easy to update or hand off.
<ferry location=0 time=2045>
<day>1</day>
<day>2</day>
<day>3</day>
<day>4</day>
<day>5</day>
</ferry>
<ferry location=0 time=0800>
<day>6</day>
</ferry>
You will need something like a database to hold the schedule data. That will help you to seperate code from data. I'm not familiar with Android but i think there is a interface to sqlite database on the device.
Further, as this is an application on a small device you may connect to the schedule database on a server thru the internet connection. That way you have to maintain schedule data only in one place (on the server) and clients will use always up to date data.
I have totally strange problem on one of my machines. I've written a program which is monitoring events from our servers and displays them on a monitoring pc. However, each event status message also contains a TIMESTAMP which is being retrieved by the following calls:
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
with
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
I'm expecting this call to return the local time, which is and was working great until today. But now my program shows me the local time +3 hours on every incoming event. A restart of the jar file does not help at all and the System Time is also set up correctly. This program is running on a machine which is synchronizing its time with an central corporate clock.
Can anyone explain me the mentioned behavior and/or state a possible solution which is not "restart the machine and try again" :-) ?
Cliffs:
- Retrival of Time is working on my- or any other machine when I start the Program
- The target Machine is running 24/7 and is only a monitoring machine, so no one is changing any options there
- It worked fine until today.
- All Time/Timezone settings on the Hostsystem (Windows XP) are correct. (checked via CMD -> "date" and also over the System Preferences)
I appreciate any kind of answer to this issue. Thank you for your time!
the Question is answered since the 25 already. I've implemented a explicit call of Timezone.setDefault() to make sure that the proper timezone is being shown the whole time. I'll close this Question now.
Thank you all for your answers!
This code:
cal.getTime()
Returns a Date object. A Date object is simply a wrapper for the UTC time as a long. In the code you showed us, it is just as correct to do sdf.format(new Date());
What is the format DATE_FORMAT_NOW? I assume you specify this yourself. Do you specify the timezone in this format?
EDIT As you mentioned in your comment, DATE_FORMAT_NOW does not specify a timezone. You should do both Timezone.getDefault() and sdf.getTimezone() to see if the value has changed to your locale + 3 hours.
EDIT2 I found this forum post about the time sporadically changing. In this case it was caused by an Oracle driver calling Timezone.setDefault(...) in the middle of a method, then setting it back afterwards.