0

I am trying to create my own Alarm Android application. I want to achieve that when alarm is triggered, MainActivity is resumed (not created again). It basically means that if I set alarm and leave my application, I want that application to be resumed when alarm is triggered.

Currently, I am facing a problem that when alarm is triggered while my application runs in background and I click on application icon, onCreate method is called and basically two instances of application are running simultaneously (I have used Toast messages to confirm this). I expected that click on application icon will cause its resuming if it is already running in background, but it seems it is not the case.

Also, I have tried procedure explained here: Resume activity in Android but it didn't work for me, Toast message from onCreate method appears on screen.

Can anybody help, please? I am really running out of ideas here. Thanks in advance!

Darian Pudic
  • 45
  • 2
  • 10
  • What do you mean by "click application icon" where? And if by that you only mean sending it to background and re-opening it then it has nothing to do with your alarm service probably. – ivan Nov 15 '19 at 23:41
  • Ivan, thank you for answer. By clicking application icon, I meant clicking on this: https://drive.google.com/file/d/12xogGgJ0z2oMc6b9UuMEI2JhxD6ORY-g/view?usp=drivesdk In other words, I meant exactly what you wrote: sending it to background after setting alarm time and reopening it when alarm triggers – Darian Pudic Nov 16 '19 at 00:26
  • You can use `singleInstance` launch mode, but the fact that your app wasn't killed to reclaim memory cannot be guaranteed. – EpicPandaForce Nov 16 '19 at 03:25
  • EpicPandaForce, thank you for your answer. I have tried, but unfortunately, it doesn't change anything - onCreate method is called again when I reopen application. Instead of resuming, application is started again, so two instances of application are running in parallel. Any other suggestion? – Darian Pudic Nov 16 '19 at 11:39

1 Answers1

0

What you need to do is specify your activity's launch mode to singleTask or singleInstance. To do this, go to your AndroidManifest.xml and change/add launchMode to your activity.

<activity
    android:name=".YourActivity"
    android:label="Your Activity"
    android:launchMode="singleInstance">

More info on the differences of different launch modes are explained here: https://developer.android.com/guide/topics/manifest/activity-element

noahutz
  • 1,207
  • 1
  • 9
  • 11
  • noahutz, thank you for answer. I've just tried with singleInstance and after that with singleTask and unfortunately, the behavior is the same - I see that onCreate method is called again and I notice that two instances of app are running simultaneously. Any other suggestion? – Darian Pudic Nov 16 '19 at 11:04