LoginSignup
0
0

アラームの停止機能

Posted at

実装した機能

アラームが鳴っている間、ポップアップを表示する。
ポップアップのボタンからアラームを停止させる。

前提

アラーム音声は10秒毎に繰り返し再生される

作業

ポップアップ表示

モーダルライブラリを使用しました。

node.js
npm install react-native-modal
import Modal from 'react-native-modal';
{showPopup && (
<Modal isVisible={showPopup} style={styles.modal}>
    <View style={styles.popupContainer}>
        <Text style={styles.popupText}>アラームを停止しますか?</Text>
        <TouchableOpacity
          style={[styles.popupButton, { backgroundColor: '#007AFF' }]}
          onPress={() => handlePopupButtonPress(stopAlarm)}
        >
          <Text style={styles.popupButtonText}>はい</Text>
        </TouchableOpacity>
      </View>
    </Modal>
  )}

アラームの停止

  1. 現在なっているアラーム音声の停止をおこなった。

    const stopAlarm = async () => {
        if (sound) {
          clearInterval(alarmIntervalId); // インターバルの停止
          await sound.unloadAsync();
        }
      };
    

    unloadAsync()は非同期関数だから、awaitがある?async()で囲っているのはなぜ?
    という疑問が湧いてきました。
    asyncとawaitについては、以下の記事がわかりやすかったです。

  1. インターバルの停止
    10秒毎に音声を再生させていたため、そのsetInterval関数も停止した。

    import Modal from 'react-native-modal';
    
    const [alarmIntervalId, setAlarmIntervalId] = useState(null)
    
    const checkAlarms = async () => {
        for (const alarm of alarms) {
          const alarmTime = alarm.time;
          const currentTime = new Date();
    
          // アラームの設定された時間(時、分)が現在の時間と一致するかどうかを確認
          if (
            alarm.isActive &&
            alarmTime.getHours() === currentTime.getHours() &&
            alarmTime.getMinutes() === currentTime.getMinutes()
          ) {
            // 10秒ごとに音声を再生
            const intervalId = setInterval(() => {
              playAlarmSound();
            }, 10000);
    
        /// 中略 ///
        
            // stopAlarm() を呼ぶために intervalId を state に保存
            setAlarmIntervalId(intervalId);
          }
        }
      };
    
    const stopAlarm = async () => {
    if (sound) {
        clearInterval(alarmIntervalId); // インターバルの停止
        await sound.unloadAsync();
      }
    };
    

    intervalIDをわざわざコンポーネント外のステートに保存した理由は?
    ポップアップ画面でのボタン押下時にintervalIDを流し、clearIntervalでインターバルを止めるため。
    useStateに入れるのがbestかは不明。。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0