Android - Tamagotchi, a game in the background

I am trying to create a Tamagotchi game with Unity for Android. Tamagotchi has a food attribute that should drop even when the Game is closed.

So my approach would be to create an IntentService that contains variables, increasing and decreasing them if necessary. For Batterie reasons, I would use the Alarm manager to start the service only every 10 minutes if the application is closed. If the application is running, it will bind the service so that it never closes, and I can get the variables.

Is there a more efficient way to handle this? I do not want my application to discharge too much.

€: If the power gets low, it should also display a notification.

+4
source share
2 answers

There is indeed a more efficient way to handle this.

Why don't you save the timestamp when the user closes the application and calculates the time elapsed after the user opens the application again? Then you can calculate the new food attribute that you made.

Edit: if you want to show notifications, if the food is low, you need an alarm manager.

Here is a sample 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

}
+3
source

You can also calculate when Tamagotchi will be hungry before the game is closed, and set the alarm only at that moment to show a notification .. if the game did not open again, so you clear all notifications.

+2
source

Source: https://habr.com/ru/post/1589202/


All Articles