Set alarms in BACKGROUND via the android AlarmClock class
I’m making an app and setting an alarm is one of the features. I don’t need the app as a standalone alert manager right now. So, I set the ACTION_SET_ALARM of the alarm class by AlarmClock using the following code :
Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
i.putExtra(AlarmClock.EXTRA_HOUR, hour);
i.putExtra(AlarmClock.EXTRA_MINUTES, minute);
i.putExtra(ALarmClock.EXTRA_MESSAGE, "Good Morning");
startActivity(i);
It can meet the requirements well. But my app automatically sets the alarm when the button is pressed after turning on the system’s default clock. I don’t need this to happen.
I need to press the button, I need to set an alarm (which is happening now) but I don’t need the system’s clock app to appear. I’ve seen some apps that meet my requirements.
Please help me not to open the clock app after setting alarm/setting alarm in the background.
Hopefully I’ve made my question clear.
Solution
I found a way by reading the API :). You must use EXTRA_SKIP_UI to set to true.
Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
i.putExtra(AlarmClock.EXTRA_HOUR, hour);
i.putExtra(AlarmClock.EXTRA_MINUTES, minute);
i.putExtra(AlarmClock.EXTRA_MESSAGE, "Good Morning");
startActivity(i);
As described in the API
If true, the application is asked to bypass any intermediate UI. If
false, the application may display intermediate UI like a confirmation
dialog or settings.
I tested it myself, and if using this EXTRA, it prompts for a toast that has set an alarm without using any other app.
Edit
For completeness, you need to add permissions:
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"></uses-permission>
The first time I forgot to set this permission, to my surprise it still works in the emulator but crashes in the device.