Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set alarm through android AlarmClock class in BACKGROUND

I am making an app and setting alarm is one of the feature. I don't need the app to be a stand alone alarm manager for now. So, I am setting alarm through AlarmClock class's ACTION_SET_ALARM 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 works fine fulfilling the requirement. But my app opens the system's default clock post setting the alarm automatically on button press. I don't need this to happen. I need to press the button, the alarm needs to set (which is happening now too) but i don't need the system's clock app to show up. I have seen some apps do what i require.

Kindly help me in setting alarm in background / not open the clock app after setting the alarm. Hope i have conveyed my question clear.

like image 337
Indrajith Nandhikeswaran Avatar asked Dec 07 '16 04:12

Indrajith Nandhikeswaran


Video Answer


1 Answers

I have found a way by reading the API :). You have to use EXTRA_SKIP_UI 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);

like stated out 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 by myself and if using this EXTRA, it has prompted a Toast that the alarm is set without using any other app.

EDIT

Just for completeness, You need to add the permission:

<uses-permission android:name="com.android.alarm.permission.SET_ALARM"></uses-permission>

I first forgot to set this permission, and to my surprise it worked nevertheless in emulator, but crashed in device.

like image 87
Opiatefuchs Avatar answered Sep 28 '22 14:09

Opiatefuchs