In my android application I want to get location updates only for certain time interval say like from morning 9 to evening 9.
How is that doable. Please share your thoughts on it.
Thanks in Advance.!
This is my solution to this problem.
use it in a running background service or something like this:
Calendar c = Calendar.getInstance();
int hofday = c.get(Calendar.HOUR_OF_DAY); //getting the current hour of day
if (hofday<21 && hofday>9){ //between 9am. and 9pm.
//start collecting gps data
}
else{
//it is not between 9am. and 9pm.
}
You set an alarm for 9 am and 9 pm. Then in your broadcast receiver for the first you turn on location updates, and for the second you turn it off.
This is a good tutorial on how to schedule repeating alarms. For location updates I recommend using LocationListener.
Related
I searched the Internet for an answer but have not found anything.
I wrote an app where every 17 minute an SMS must be sent ( every 17 minute means: 10:17:00 and not at 10:17:49 )
Therefore, I use an AlarmManager with setExactAndAllowWhileIdle, and AlarmManager.RTC_WAKEUP.
Long whenToFireOff = treeMapInstance.getFirstEntryInTreeMap().getKey();
Calendar alarmCal = Calendar.getInstance();
alarmCal.set(Calendar.HOUR_OF_DAY, treeMapInstance.convertMillisecondsToHour(whenToFireOff));
alarmCal.set(Calendar.MINUTE, treeMapInstance.convertMillisecondsToMinutes(whenToFireOff));
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmCal.getTimeInMillis(), pi);
However, it gets always triggered round about 10:17:49, and the next scheduled alarm also at 10:34:49, and so on.
I calculated my next alarm correctly. I am absolutely 100% sure :)
Is setExactAndAllowWhileIdle not as exactly as it is written in the documentation?
Thanks
I want to get a hard location fix every certain minutes & a soft location fix every certain minutes and if user has moved more then certain meters. I been testing the logic with following piece of code walking (tried it with larger parameters as well while driving) but it doesn't really return me periodic location fixes. It would return a location fix right away when request starts then sometime return 1 location fix few minutes later that but then for up-to an hour it won't return a location fix.
LocationRequest locationRequest = LocationRequest.create();
int priority = PRIORITY_BALANCED_POWER_ACCURACY;
locationRequest.setPriority(priority);
locationRequest.setInterval(localInterval); //set to 6 minutes
locationRequest.setFastestInterval(localFastestInterval); //set to 3 minutes
locationRequest.setSmallestDisplacement(smallestDisplacement); //set to 10 meters
locationRequest.setNumUpdates(numUpdates); //set to Int.MAX_VALUE
locationRequest.setExpirationDuration(expirationDuration); // set to Long.MAX_VALUE
LocationServices.FusedLocationApi.requestLocationUpdates(locationClient, locationRequest, pendingIntent);
If I set displacement to 0 then I get periodic location updates. Any idea what is going on?
After long exhaustive testing & experimentation I've found that if you don't call setFastestInterval you will get periodic updates exactly according to the interval set with setInterval.
However as other applications can cause location fixes to be delivered very fast to you so just put a check for ignoring location fixes delivered faster than a certain threshold of time passed.
According to documentation: If setFastestInterval(long) is set slower than setInterval(long), then your effective fastest interval is setInterval(long) but that doesn’t happen: e.g. setting following parameters should give you a hard location fix every 1 minute but it does not (on Marshmallow at-least):
interval = 1 min
fastestInterval = 20 min
displacement = 0
If anyone can disprove my findings with a piece of code that would be great.
We're making a game in Android Studio and we got stuck. The resource (mana) used for specific spells should recover on time, e.g. 1 mana point per 5 minutes. We don't really get how to make it recover while the game is off. Is there a method to check current date/time and count the amount of mana replenished? Converting date and time to String and comparing it with the new date/time seems to be an "exciting" work to do, but we would bypass these mechanics if there is a way.
Thank you in advance.
The best way to do this in the background is to register a receiver in your manifest. This means the receiver will keep listening for broadcasts even if the app is off.
What you need is this particular action when registering your receiver Intent.ACTION_TIME_TICK
There is a more detailed answer about this matter here Time change listener
Another solution is to use the Calendar class in java. With it you can get the exact minutes passed from a point in the past to this moment. This way you don't have to worry about parsing dates and similar. I can't provide you specific examples because me myself have not used the Calendar class very much, but I'm sure you can find lots of stuff in the official documentation and on stackoverflow about it.
No need to work with Date objects, the simple usage of System.currentTimeMillis() should work. Here's a basic outline:
long mLastManaRefreshTime = System.currentTimeMillis();
void refreshMana()
{
long timeDelta = System.currentTimeMillis() - mLastManaRefreshTime;
mLastManaRefreshTime = System.currentTimeMillis();
float totalManaToRefresh = (float)AMOUNT_TO_REFRESH_IN_ONE_MINUTE * ((float)timeDelta / 60000f);
mMana += totalManaToRefresh;
if (mMana > MAX_MANA)
mMana = MAX_MANA;
}
This method is of course just an outline. You will need to call this once every update cycle. It will calculate how much time passed since the last time refreshMana was called, and replenish the required amount.
If you need this to work while the game is off, you can save the mLastManaRefreshTime to a SharedPreferences object and reload it when the game loads up again.
With System.currentTimeMillis() you can a current time-stamp in milliseconds.
You could save the latest time-stamp in your Preferences with every 5 min tick of the running game. For the other case, when your App comes back from a state where it does not do this (i.e. called the first time, woken up etc.).
Something like this:
int manacycles = ((int) (((System.currentTimeMillis() - oldtimestamp) / 1000) / 60) ) % 5;
would give you the number of Mana points you would have to add.
Alternately you could do the same thing with the Calendar class.
Also keep in mind players could cheat this way by simply changing their time. If your game is online you could get the time from the internet, with something like this:
try {
TimeTCPClient client = new TimeTCPClient();
try {
// Set timeout of 60 seconds
client.setDefaultTimeout(60000);
// Connecting to time server
// Other time servers can be found at : http://tf.nist.gov/tf-cgi/servers.cgi#
// Make sure that your program NEVER queries a server more frequently than once every 4 seconds
client.connect("nist.time.nosc.us");
System.out.println(client.getDate());
} finally {
client.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
I am using AlarmManager in my application to set alarm for a particular time. I have used AlarmManager.RTC_WAKEUP to set the alarm. When I am testing the same it's working on number of device like Lg optimus, Sony Xperia etc. But while testing the same app in Samsung Galaxy S3 I found that alarm is not working. I am still unable to understand why is this happening.
I am using following code to set alarm :-
// create the object
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP,cal1.getTimeInMillis(), PendingIntent.getBroadcast(getActivity(),reminderId, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Someone please help me to solve this strange problem. Any help would be appreciable.
Thank you
I'm not sure but it sounds the problem is with the way you set cal1's time and maybe different timezone.
I'm not sure what the particular issue you are having is, but you could try to replace cal1.getTimeinMillis() with System.currentTimeMillis() + your time delta in ms. This works consistently for me.
Is your testing getting tripped up by the long-time Android OS bug https://code.google.com/p/android/issues/detail?id=2880 ? If the clock gets set backwards, Intent.ACTION_DATE_CHANGED broadcast won't be delivered until the clock catches up to what was going to be the alarm time. (Reboot to reset this broken state.) That's because this Intent is based on an AlarmManager alarm which does not get updated when the clock changes.
That situation is pretty rare in normal use. But it occurs frequently when testing alarm code.
If you're testing an AlarmManager alarm by adjusting the clock, AFAIK any alarm set to a target Calendar on any Android device will get messed up by adjusting the clock. You can work around it by rescheduling your alarm whenever the clock gets adjusted. This assumes the system properly broadcasts Intent.ACTION_TIME_CHANGED so you can tell when the clock gets adjusted. (That Intent is misnamed. It's not like Intent.ACTION_DATE_CHANGED which occurs when the date changes due to time passing.)
I think you have problem in your "cal1" object;
When you set time in calendar object, actually setting Month, you should not use exact numeric value of month;
ex: - April = 4, you must use 3 instead of 4
I face this problem in API Level 19, but don't know about others.
This Question may give you better explanation.Why month give wrong value
public Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,2014);
c.set(Calendar.MONTH, 03);//One minus from actual month numeric value
c.set(Calendar.DATE, 24);
c.set(Calendar.HOUR_OF_DAY,16 );
c.set(Calendar.MINUTE, 39);
c.set(Calendar.SECOND, 0);
am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),pi);
I am an android developer.I am making an application in which I have to take user input like
8:00,9:00,10:00 etc and I have to set alarm for 20 or 30 days for each time user enter .A user can enter two or three or any times the timings.I know there is a function
alarm.setRepeating(AlarmManager.RTC,System.currentTimeMillis()+timeinminutes*60*1000,30*1000, pintent);
But I have to set the alarm for ever or days entered by user .So can any body tell me .How can I do this .
the following code help you,firstWake the app will run at very fast time,you can specify as your requirements
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
long interval = android.text.format.DateUtils.DAY_IN_MILLIS*20;//or 30
long firstWake = System.currentTimeMillis() ;
am.setRepeating(AlarmManager.RTC,firstWake, interval, pendingIntent);
Maybe you can use another nonrepeating alarm for 20 or 30 days that stops repeating alarms.