0

Hi and thanks for your help.

I have the following situation.

I have an AlarmManager that fires off a Service every 1 minute.

I have to execute a specific method in that Service only when the Service is started for the first time. not when it starts the subsequent times.

I do not think shared preferences is a solutions, because they are persisted if the phone is switched off.

Please how do I solve this ??

Thank you for any suggestion!!!

Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
Lisa Anne
  • 4,482
  • 17
  • 83
  • 157
  • I would add a service or a broadcast to the alarmmanager that would be fired first and only once to reset the content of the shared pref. Or, maybe you can write to a file in /tmp, which should be deleted at reboot – njzk2 May 27 '13 at 15:45

2 Answers2

1

You can call it in onCreate(). See here in the official documentation. It says:

Called by the system when the service is first created. Do not call this method directly.
For your reference you can see the question When does Application's onCreate() method get called? and If android restarts a Service is onCreate called again?

Community
  • 1
  • 1
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
  • but it could be created a second time, even though it has run always. – Dory Zidon May 27 '13 at 15:44
  • Yaa if it was killed sometime and then restarted. So, even if it gets killed you don't want to call your code? You only want to just call it once if the whole lifetime of the app. – Shobhit Puri May 27 '13 at 15:46
1

Try inheriting form the App and store in it..

public class YourApp extends Application {

private static boolean mFirstRun = false;

public static boolean getFirstRun() { return mFirstRun; }
public static void clearFirstRun() { mFirstRun = false; }

from your service:

if (YourApp.getFirstRun()) 
{
   clearFirstRun();
   // run first time code
}
Dory Zidon
  • 10,497
  • 2
  • 25
  • 39