my problem is that I want to run a service that compares the current time of the device. And a "x" hour make some things.
But I don't have idea how can I make that.
Thank you a lot
Schedule a repeating alarm using AlarmManager (see this training lesson).
Then in the BroadcastReceiver, compare the current time with the list of times when you want to do some things if matches do it.
You can start a thread in your service which checks the time at particular intevrvals. These intervals can be defined by you by putting this statement:
Thread.sleep(time_in_milliseconds);
in your Thread's "run" method.
You can then use the SimpleDateFormat class to get the current time and compare hours with desired value. Once it is equal to the desired value, you can perform whatever task you wanted to do. Consider going through the SimpleDateFormat oracle docs for more detail and learning about Threads in case you don't know anything about them.
Related
I need execute an action on a specific date
Handler(Looper.getMainLooper()).postAtTime({
texto.text = "Testo ha cambiado"
},2020-02-12)
postAtTime takes a milliseconds value. You'll need to use some date library (like Date) to create an object representing the date you want. Then use its "convert to milliseconds / Unix time" method (for Date it's getTime()) to get a value you can pass to postAtTime
But if you post a message to the Handler, your app will need to stay running the whole time until the time your message is handled. If the app is closed (including by the system) that message is gone. And your app needs to be running in the foreground when it happens too. It's not meant for scheduling important events that have to happen even if the app is closed, and it's really not meant for things way off in the future
You probably want to use AlarmManager
Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.
(there's also WorkManager which isn't about a specific time but might be better for whatever you're doing)
Heyyy, I know how to save variables and other data in SharedPreferences, but I like to know how it would be possible to decrement a variable daily.
Already this var (int) will be in the Shared Preferences, and every day we decrements of -1.
How could I decrement, knowing that the user does not necessarily open the app every day for example?
Have a good day :)
Save the original date, when the application is opened check for current date and you know what your variable should be :)
If you want to decrement the variable on Daily Basis then
Implement a BroadcastReceiver and declare it in AndroidManifest.xml with action android.intent.action.DATE_CHANGED. This would run the BroadcastReceiver once in a day when the date is changed.
In onReceive() method you can place code (validations) and persist results into SharedPrefs.
Note:
1. Service would incur huge running cost.
2. Activity would run the same code everytime it opens but BroadCast would run it once a day in a clean and independent fashion.
You might need a Broadcast action BOOT_COMPLETED as if the device is turned on (reboot).
You have several choices:
Every time your app starts, load the value from Shared Preferences and decrement it by the number of days which have passed.
Write a service which decrements the values every day.
Write a BroadcastReceiver which starts when the date changes.
I think using JobScheduler would be a nice way to implement this. It's available from API 21 and allows the app to execute actions under certain circumstances, even if it's not open. Here's the official doc, and a nice tutorial here.
My application is time dependent and I don't want change in device date and time affect my application, like if user deliberately set device date to any previous date . Is there any way to get current date and time when user is connected to mobile network or WiFi I don't want to use GPS.
Javadoc of the SystemClock class describe different ways of counting elapsed time for various scenarios and conditions.
In your case you have to use
long time = SystemClock.elapsedRealtime();
Return the time since the system was booted, and include deep sleep.
This clock is guaranteed to be monotonic, and continues to tick even
when the CPU is in power saving modes, so is the recommend basis for
general purpose interval timing.
Call it for the first time when you want to start tracking the use of Network (I assume you already know how to do it) and store that value.
When you receive event about user not using network anymore, call the same method again and calculate spent time.
long elapsed = time - SystemClock.elapsedRealtime();
Next you can transform milliseconds to String for example like this:
String formattedElapsedTime = DateUtils.formatElapsedTime(elapsed/1000);//note that this method takes second as arguments so we have to divide it by 1000
You should call webservice and get current date and time of server. Then server would be responsible for the actual date/time. Best way is to build your own webservice, because it gives you more control than using third party.
I want to run a function from my Android application at a fixed time (let's say 8am) on the first day of every month. The function, depending on user's preferences, will either serve a notification or start downloading a file over the Internet (both of which are already taken care of) or do nothing.
I tried using BroadcastReceiver with action android.intent.action.DATE_CHANGED but I read that it is fired only when user changes the date manually (although even then it worked the first 2-3 times I tried and then stopped working). I think an AlarmManager will be able to do what I need done but not really able to figure out how to implement it.
This should run whether or not my application is active/running. What is the optimum way to do this? Any supporting code will be appreciated.
Just start a service when start up. In the service,you could check the date in another thread.
Use an alarm
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()/*now*/, TIME_REPEATING, pendingIntent);
The TIME_REPEATING will be your calculate of the first day on the month, and the pendingIntent your service to run the task.
The unique hard work will be know how many time need to pass to the first day of the next month. But it's possible and very pausable to calculate.
I want to design app in which I can get the time before the user has changed to any new time.
I am using
android.intent.action.TIME_SET
To know that user has changed time
eg. Suppose current time is 10.00 pm User changed it to 09.00 pm So can i get previous time that is 10.00 pm
Question was asked some time ago, but I have generally the same problem and cannot find reasonable (efficient) solution.
Just to recall, I want to know the time that was set before user changed time. For example, user changed time from 6:12 PM to 3:21 PM. To the best of my knowledge, there is no information about previous time in android.intent.action.TIME_SET. But when handling this intent I want to somehow know that the time was set to 3:21 PM when there actually was 6:12 PM.(let assume the same day).
According to accepted answer to this question:
android detect user modifying device clock time
If I want to handle situations when network is not available, I have to kind of append my own timer to my application, measure time on my own, and when handling
android.intent.action.TIME_SET
get old time from this built-in timer.
But it seems to me, that this is quite heavy solution and I reckon there must be simpler way to do this.
So the question is, what is the best (most efficient and the most simple) way to handle situation described above. Despite this problem seems to me very common, I couldn't find fair solution.
You could try to monitor the difference between System.currentTimeMillis() and SystemClock.elapsedRealtime(). The value of System.currentTimeMillis() would be affected by the change of system time whereas the value of SystemClock.elapsedRealtime() would not.