admin管理员组

文章数量:1123591

I have repeatedly attempted to add features that can let users cancel android alarm clock that announces the current time using android Text to Speech engine for ten minutes, but it has failed to cancel.

The alarm vibrates once and then continuously announces the current time for ten minutes. I now want to add a stop button that can be used to cancel the alarm when pressed, but all my attempts have failed. Below is my code

public class AlarmReceiver extends BroadcastReceiver {
    private TextToSpeech textToSpeech;
    private Handler handler;
    private PendingIntent pendingIntent;
    private Context appContext;
    private final int totalDuration = 10 * 60 * 1000; // 10 minutes
    private long startTime;
    private boolean isAlarmStopped = false; // Alarm stopped flag

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("AlarmReceiver", "onReceive() called");

        appContext = context;

        // Check if the alarm should be stopped
        if (intent.getBooleanExtra("STOP_ALARM", false)) {
            stopAnnouncements();
            return; // Immediately exit to prevent further execution
        }

        if (isAlarmStopped) {
            Log.d("AlarmReceiver", "Alarm already stopped.");
            return;
        }

        Log.d("AlarmReceiver", "Starting alarm sequence.");

        // Vibrate the device
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        if (vibrator != null) {
            vibrator.vibrate(2000); // Vibrate for 2 seconds
        }

        // Initialize Text-to-Speech only once
        if (textToSpeech == null) {
            textToSpeech = new TextToSpeech(context, status -> {
                if (status == TextToSpeech.SUCCESS) {
                    textToSpeech.setLanguage(Locale.getDefault());
                    startTime = System.currentTimeMillis();
                    startAnnouncingTime();
                }
            });
        } else {
            startAnnouncingTime();
        }
    }

    private void startAnnouncingTime() {
        handler = new Handler(Looper.getMainLooper());
        Runnable timeAnnouncer = new Runnable() {
            @Override
            public void run() {
                // Check if the alarm was stopped
                if (isAlarmStopped) {
                    Log.d("AlarmReceiver", "Stopping announcements due to stop flag.");
                    return; // Exit without rescheduling
                }

                // Announce current time
                Calendar calendar = Calendar.getInstance();
                String timeText = String.format(Locale.getDefault(), "The current time is %d:%02d",
                calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE));

                if (textToSpeech != null && !isAlarmStopped) {
                    String utteranceId = "TTS_Alarm"; // Use a unique identifier for announcements
                    textToSpeech.speak(timeText, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
                }

                // Reschedule if not stopped
                if (!isAlarmStopped) {
                    handler.postDelayed(this, 5000); // Reschedule after 5 seconds
                }
            }
        };

        handler.post(timeAnnouncer);

        Log.d("AlarmReceiver", "Running timeAnnouncer, isAlarmStopped: " + isAlarmStopped);
    }

    private void stopAnnouncements() {
        Log.d("AlarmReceiver", "Stopping alarm and announcements.");

        // Set the stop flag
        isAlarmStopped = true;

        // Stop handler tasks immediately
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            Log.d("AlarmReceiver", "Handler callbacks removed.");
        }

        // Stop TextToSpeech if initialized
        if (textToSpeech != null) {
            Log.d("AlarmReceiver", "Stopping TextToSpeech.");
            textToSpeech.stop(); // Stops all ongoing speech
            textToSpeech.shutdown(); // Full shutdown
            Log.d("AlarmReceiver", "TextToSpeech successfully stopped and shutdown.");
        }

        textToSpeech = null; // Ensure nullification occurs here

        // Stop vibration
        if (appContext != null) {
            Vibrator vibrator = (Vibrator) appContext.getSystemService(Context.VIBRATOR_SERVICE);
            if (vibrator != null) {
                vibrator.cancel();
                Log.d("AlarmReceiver", "Vibration canceled.");
            }
        }

        Log.d("AlarmReceiver", "Alarm completely stopped.");
    }
}

本文标签: alarmmanagerI39m unable to cancel android alarm clock when it startedStack Overflow