I try to build a Tamagotchi game with Unity for Android. The Tamagotchi has a food attribute that should go down even when the Game is closed.
So my approach would be build a IntentService that holds the variables, increase and decrease them if needed. For Batterie reasons i would use Alarm manager to start the Service only every 10 minutes if the App is closed. If the app is started it would bind the Service so it never closes and i can get the Variables.
Is there a more efficient way to handle this? I dont want my app to battery drain too much.
€:
If the food gets low it should also display a notification.
There is indeed a more efficient way to handle this.
Why don't you just save a timestamp when the user closes the app and calculate the time passed when the user opens the app again?
Then you can calculate the new food attribute you're done.
Edit: If you want to show notifications if the food is low you need the alarm manager.
Here is some example code:
public static void registerAlarm(Context context) {
Intent i = new Intent(context, YOURBROADCASTRECIEVER.class);
PendingIntent sender = PendingIntent.getBroadcast(context,REQUEST_CODE, i, 0);
// We want the alarm to go off 3 seconds from now.
long startTime = SystemClock.elapsedRealtime();
startTime += 60000;//start 1 minute after first register.
// Schedule the alarm!
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, startTime, 900000, sender); // 15min interval
}
You can also calculate when the Tamagotchi will be hungry just before the game is closed and set alarm only to that point to show notification.. unless the game opened again so you clear all notifications.
Related
I have an android app where I am trying to play videos based on the server's clock time(not the android device's clock time which might be different)
08:00:00 - 08:04:59 -> video_url_1
08:05:00 - 08:09:59 -> video_url_2
08:10:00 - 08:14:59 -> video_url_3
So when the user opens the app,if the server's clock time falls in the above category,then the respective videos are played,otherwise a timer for remaining seconds is shown based on the server's clock time.
If the android app is already open,then it should automatically start playing video when the server's clock time falls in any of the above categories.
Continuously pinging the server for its clock time is not a good option.So how can we achieve the above functionality?
I think Alarm Manager is your solution.
The flow would be the following:
Android app opens and request the server what the server time is and when is the next video.
Calculate how in how many minute or seconds the time will be done.
Setup an alarm in the device for that time. Let's say the server time is 8:45 and the next video is at 9:30. So you know 45 minutes has to pass in order to be able to play the video. So the alarm should be trigger in 45 minutes.
When the alarm is trigger, check the server again and if it's fine, play the video and schedule your next alarm (for the next video or if the server now wants to play the video in another moment), if the user fake his time, then recalculate the time that need to pass and reschedule your alarm.
Set the alarm manager example to trigger a broadcast receiver:
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(context, MyBroadCastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
// add here your calculate minutes or seconds or hours
calendar.add(Calendar.MINUTE, 45);
if (alarmManager != null) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
Then have your broadcast receiver to handle any other action:
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Do your magic, could be play the video or show a notification saying the video is ready to play
}
}
If you want more information about the alarms in Android, take a look at this link:
https://developer.android.com/training/scheduling/alarms.html
In my app, I want to kick off an timer that triggers an action every x minutes, regardless if the user is currently in the app or not. I have been reading around and am not sure which combo of Broadcast and Receiver types I should use - any guidance would be helpful.
Example of user actions:
User hits a button, sets initial timer (alarm)
Timer is reached, trigger an action and set the timer again
Repeat until it has run for x minutes
when the user hits button set alarm as
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.setRepeating (AlarmManager.Type,
long triggeringtime,
long interval,
PendingIntent operation);
here triggeringtime is how to time it shud take to take an action
and interval how to much time it would take to do the same.
here operation is the Intent which you need to execute like it may be an activity or Service you can Define it as
operation = PendingIntent.getActivity( context, 0, intent or service, 0);
2 and 3 step will be continuously run thats what the alarm manager does.
This alarm continues repeating until explicitly removed with
cancel(AlarmManager.OnAlarmListener).
I am a beginner Sry if i wrong. Hope it helps!
Android JobScheduler
You can find a lot of tutorial online.
I'm trying to create a function in my App, which notifies the user at the expiration day of his rented books. I'll work with checkboxes in a listview, as below:
(Dates are for show purposes only)
Now i'm wondering how can i do it the best way. I'm having experiences with AlarmManager and BroadcastReceivers, but I didn't get a clear flowchart yet.
Thats because I need to set an specific alarm to each book and cancel that specific alarm when requested. Also, it needs to reactivate all Alarms when device is restared (by calling BOOT_COMPLETE broadcast).
PS.: Alarms will usually be set to one week after current date.
PS2.: Can I use Calendar to do it? I mean, this way i wouldn't have to reactivate all alarms, or calculate (expirationDate - currentDate) in millis.
Can someone, who has an idea, try to show me the way? Thanks!
I think the key would be to give each and every book its own alarm id as soon as you set the alarm for this book for the first time.
Then you should keep a list of the running alarm ids and timestamps (maybe in SharedPreferences).
With a method like this you can cancel a specific alarm with regards to its alarm id:
public static void cancelAlarm(Context context, int alarmId) {
PendingIntent pi = PendingIntent.getService(context, alarmId,
new Intent(context, YourService.class),
PendingIntent.FLAG_NO_CREATE);
if(pi!=null) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pi);
}
}
When you receive the BOOT broadcast, you can get the list of alarm ids together with timestamps from SharedPreferences and start all the alarms with their respective alarm ids
I am building a reminder application where the user enters an event into an SQLite DB. The main screen lists the title of each reminder and clicking an item shows the details of it. All of this works fine.
Now I want to allow the user to set up notifications for each item, being given an option to set a reminder for 15 mins, 30 mins, or 1hr before the event is scheduled.
I have no clue how to go about this and can't find any good tutorial on it. Can anyone give me some idea as to how I might implement this?
Thanks!
Use the AlaramManager to fire a broadcast that will tell your app to show a notification to the user about the event.
Here is an example of using it: Alarm Manager Example
Once you get the date of the event from the database, it's as easy as any other notification, just keep in mind that you'd subtract the amount of time (the 15,30,60 minutes) to the date.
Timer timer = new Timer();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm");
Date date = formatter.parse("11/08/2012 16:39");
timer.schedule(timerTask, date);
This will schedule the event to the event time, and I'm understanding you want a reminder before the event actually happens. To do this you can create a calendar object to modify the date in the means you need. Remember to remove the previous schedule or you will be left with two reminders (one at the time, and one as a reminder).
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MINUTE, -15);//Or whatever
//Then schedule it.
time.schedule(timerTask,cal.getTime());
Both approaches are using the variable timerTask which could be something like this, involving the createNotification method call that will in fact create the pending notification.
TimerTask timerTask = new TimerTask(){
#Override
public void run(){
createNotification(title, text, tickerText, millisec);
}
};
There is a potential issue with this thou. If the application is closed, I believe the timer dies with it, so depending on the nature of your application you may want to use the AlarmManager as others have suggested.
You'll use the AlarmManager to set the action to be triggered on the specific date/time. (there're A LOT of tutorials on how to use the AlarmManager)
The alarm manager event always triggers a PendingIntent. From this intent you can either make a broadcast or start a service. (you'll have to create a broadcast receiver or a service)
Then on the broadcast receiver or service you build up and show the notification.
I suggest the broadcast receiver route, it's cleaner and more seamless.
you might also to have a broadcast receiver for onBoot events to re-schedule the events on the alarm manager case the user reboots the device.
I want a widget showing a countdown for a user initiated tracking of a bus departure. I want to update the widget every minute or so, from when the user initiates the tracking to when the bus has departed (i.e. the time runs out).
This widget needs to be updated more frequently than what updatePeriodMillis allows, which is every 30 minutes. I reckon about once a minute.
Being new to Android programming, I can think of a few ways to do this, but I would probably end up doing it in a way that consumes way too much battery etc, so I'm looking for some insights from more experienced Android developers.
How do I start the timer? How can I access the widget instance from my applications run-time? And so on.
I would register an alarm to start my service every 1 minute and the service would update the widget UI
final Intent intent = new Intent(context, UpdateService.class);
final PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
long interval = 1000*60;
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),interval, pending);
AlarmManager.ELAPSED_REALTIME will not wakr the device if it's sleeping to battery life should not be affected.