Reputation: 517
I hope this isn't a duplicate of a similar question but haven't been able to find anything that helped me.
I'm creating a simple egg timer, and it works very well. Though I am struggling one thing. When the timer runs out, an alarm starts and an activity shown as a dialog pops up. Though this happens only if the app i open. If I open another app and the alarm goes off nothing happens.
So my question is, how do I make the dialog pop up no matter what the user is doing?
At the moment my method for displaying the dialog looks like this:
private void ShowTimesUp(){
Intent dialogIntent = new Intent(getBaseContext(), TimesUpDialog.class);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(dialogIntent, 1);
}
and the manifest looks like this:
<activity android:name=".Home"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".TimesUpDialog" android:theme="@android:style/Theme.DeviceDefault.Dialog"></activity>
Upvotes: 2
Views: 999
Reputation: 2253
Try this:
public static final int TIMEOUT = 60 * 1000;
...
Intent dialogIntent = new Intent(getBaseContext(), TimesUpDialog.class);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent = PendingIntent.getActivity(YourApplication.getInstance().getBaseContext(), 0,
dialogIntent, dialogIntent.getFlags());
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + TIMEOUT, intent);
I think you will not need any other timer logic.
P.S.: I did not test this, hope it helps.
Edit: a possible solution for the question mentioned in below comment
Now I am just wondering if it is possible to get a result from the intent started by the AlarmManager?
The above code should be changed to this:
Intent startApplicationIntent = new Intent(getBaseContext(), MainActivity.class);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startApplicationIntent.putExtra(START_DIALOG, true);
PendingIntent intent = PendingIntent.getActivity(YourApplication.getInstance().getBaseContext(), 0,
startApplicationIntent, startApplicationIntent.getFlags());
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + TIMEOUT, intent);
Now in your MainActivity
's onStart()
method you could do the following:
boolean startDialog = getIntent().getBooleanExtra(START_DIALOG, false);
if (startDialog) {
Intent dialogIntent = new Intent(MainActivity.this, TimesUpDialog.class);
startActivityForResult(dialogIntent, REQUEST_CODE_CONSTANT);
}
Where START_DIALOG
is a String constant defining an intent extra value's key and MainActivity
is the Launcher activity.
Hope this works for you.
Upvotes: 1