[Solved] Android: Starting Alarm Service from Dialog


Your code based on Android Dev Guide is working, to be more precise, this one:

alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + 10 * 1000, alarmIntent);

Alarm.Receiver.java:

public class AlarmReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {

            /* class1 = new MainActivity();
            class1.message();*/
        Toast.makeText(context, "Don't Forget To Email Your Teacher!.",
                Toast.LENGTH_LONG).show();
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(1000);
        Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        if (alarmUri == null)
        {
            alarmUri =       RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        }
        Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
        ringtone.play();

    }
}

3 things I needed to do to make it work (on API 16 to 25):

Add permissions BEFORE application in your manifest:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.SET_ALARM" />
<uses-permission android:name="android.permission.VIBRATE" />

Move receiver WITHIN application:

<receiver android:name=".Action.AlarmReceiver"> //change according to your path
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

And finally … reboot Android Studio.
Yep, I don’t know why, but I had to do it to make it work in my case.

Hope it helps!

solved Android: Starting Alarm Service from Dialog