1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.deskclock.alarms;
18
19import android.content.Context;
20import android.media.AudioAttributes;
21import android.os.Build;
22import android.os.Vibrator;
23
24import com.android.deskclock.AsyncRingtonePlayer;
25import com.android.deskclock.LogUtils;
26import com.android.deskclock.provider.AlarmInstance;
27
28/**
29 * Manages playing ringtone and vibrating the device.
30 */
31public final class AlarmKlaxon {
32    private static final long[] sVibratePattern = {500, 500};
33
34    private static boolean sStarted = false;
35    private static AsyncRingtonePlayer sAsyncRingtonePlayer;
36
37    private AlarmKlaxon() {}
38
39    public static void stop(Context context) {
40        LogUtils.v("AlarmKlaxon.stop()");
41
42        if (sStarted) {
43            sStarted = false;
44            getAsyncRingtonePlayer(context).stop();
45            ((Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE)).cancel();
46        }
47    }
48
49    public static void start(Context context, AlarmInstance instance) {
50        LogUtils.v("AlarmKlaxon.start()");
51        // Make sure we are stopped before starting
52        stop(context);
53
54        if (!AlarmInstance.NO_RINGTONE_URI.equals(instance.mRingtone)) {
55            getAsyncRingtonePlayer(context).play(instance.mRingtone);
56        }
57
58        if (instance.mVibrate) {
59            final Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
60            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
61                vibrator.vibrate(sVibratePattern, 0, new AudioAttributes.Builder()
62                        .setUsage(AudioAttributes.USAGE_ALARM)
63                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
64                        .build());
65            } else {
66                vibrator.vibrate(sVibratePattern, 0);
67            }
68        }
69
70        sStarted = true;
71    }
72
73    private static synchronized AsyncRingtonePlayer getAsyncRingtonePlayer(Context context) {
74        if (sAsyncRingtonePlayer == null) {
75            sAsyncRingtonePlayer = new AsyncRingtonePlayer(context.getApplicationContext());
76        }
77
78        return sAsyncRingtonePlayer;
79    }
80}