12 Commits
Author SHA1 Message Date
me 025836acb6 Agent fixed the current set of issues, now the app at least runs (and is actually staying alive in the background successfully!) but the countdown is visually messed up on SDK24 (hours field is missing) and SDK36 (fields do not count down at all even though the app is making the noise), plus the Pause button no longer pauses and causes the right button to be disabled indefinitely after using it. 2026-11-09 15:13:08 -07:00
me 9ff779b26c Agent thinks it fixed the crash on SDK36 and lack of interval counting down on SDK24. 2026-11-08 19:38:16 -07:00
me 432a1394b9 main, app is now worse off after agent experimentation, crashes immediately on SDK 36 and does not count down on SDK 24, turn on DEBUG to see if anything obvious and silly is happening. 2026-11-08 15:21:04 -07:00
me 3a057f0878 Agent says it now has the app working properly with a foreground service. 2026-11-08 15:03:46 -07:00
me f59bd78716 main, more Android Studio recommendations. 2026-11-06 14:38:21 -07:00
me 01472d90fb Update AGP. 2026-11-06 14:35:02 -07:00
me f0cd128025 main, take some suggestions given by Android Studio. 2026-11-06 14:31:07 -07:00
me b7a419eeab main, fix some silliness of agent using full class path. 2026-11-06 14:30:34 -07:00
me 4ede74e7a2 Agent's attempt to ensure the sound gets played every interval (adding Looper to Handler and moving release() from playSound to onDestroy) as well as ensuring it's not delayed (using play() rather than start()). 2026-11-06 13:35:08 -07:00
me 124e1bc211 Fix some of the agent's code, mediaplayer not defined in TimerForegroundService so maybe it was intended for Main, and PowerManager's WakeLock tag wanted to know the app name with a colon for logging. 2026-11-03 13:34:31 -07:00
me 1b9f40c002 Update plugin versions. 2026-11-03 13:32:39 -07:00
me 262aa439db Model's attempt to fix: 1) Only the first itnerval making a sound, all subsequent countdowns being silent. 2) App opening up directly to the Alarms & Reminders screen to get permissions approved without any prompting the user on what is going on. 2026-11-03 13:16:32 -07:00
5 changed files with 225 additions and 139 deletions

No files matched your search

+2 -2
View File
@@ -2,11 +2,11 @@ apply plugin: 'com.android.application'
android {
namespace "com.hyperling.apps.infinitetimer"
compileSdkVersion 36
compileSdkVersion 37
defaultConfig {
applicationId "com.hyperling.apps.infinitetimer"
minSdkVersion 14
targetSdkVersion 36
targetSdkVersion 37
versionCode 9
versionName "1.1.2"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
@@ -1,20 +1,23 @@
package com.hyperling.apps.infinitetimer;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
@@ -27,7 +30,6 @@ import android.widget.SeekBar;
import android.widget.TableRow;
import android.widget.TextView;
import java.net.URI;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
@@ -43,7 +45,7 @@ public class MainActivity extends AppCompatActivity {
// Interrupt based checking would be nice
int waitInterval = 99;
boolean DEBUG, start, appOpen, serviceRunning;
boolean DEBUG=true, start, appOpen, serviceRunning;
SharedPreferences sharedPreferences;
@@ -55,12 +57,21 @@ public class MainActivity extends AppCompatActivity {
TextView tvDot;
Uri ringtoneUri;
// RingtoneManager reference for consistent notification sound playback across loops
private android.media.Ringtone notificationRingtone;
// For proper sound lifecycle management across timer loops
private Ringtone ringtonePlayer;
MediaPlayer mediaPlayer;
SeekBar seekBar;
AudioManager audioManager;
TextView tvSeekBar;
// Local broadcast receiver to update UI while app is foregrounded
private BroadcastReceiver timerUpdateReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
String tag = "onCreate";
@@ -85,6 +96,9 @@ public class MainActivity extends AppCompatActivity {
if (DEBUG) Log.d(tag, "Got strings.");
/***** Setup Local Broadcast Receiver *****/
setupTimerUpdateReceiver();
/***** Shared Preferences *****/
sharedPreferences = getSharedPreferences(keySharedPreferences, MODE_PRIVATE);
DEBUG = sharedPreferences.getBoolean(keyDebug, true);
@@ -97,8 +111,16 @@ public class MainActivity extends AppCompatActivity {
// Check exact alarm permission for Android 12+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !Alert.isExactAlarmAllowed(this)) {
if (DEBUG) Log.w(tag, "Exact alarm permission not granted, requesting...");
new AlertDialog.Builder(MainActivity.this)
.setTitle("Alarm Permission Required")
.setMessage("To ensure the timer alerts you reliably, please grant 'Alarms & Reminders' permission in system settings.")
.setPositiveButton("Grant Permission", (d, w) -> {
Intent intent = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);
startActivity(intent);
})
.setNegativeButton("Not Now", (d, w) -> d.dismiss())
.setCancelable(false)
.show();
}
if (DEBUG){
@@ -206,6 +228,20 @@ public class MainActivity extends AppCompatActivity {
if (DEBUG) Log.d(tag, "Finished");
}
private void setupTimerUpdateReceiver() {
timerUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG + "Receiver", "Received service update");
// Update UI immediately with latest countdown state from Service
String remainingTime = intent.getStringExtra("remainingTime");
if (remainingTime != null && chronometer != null) {
chronometer.setText(remainingTime);
}
}
};
}
private void doTimeChooser(){
String tag = TAG + "doTimeChooser";
if (DEBUG) Log.d(tag, "Starting");
@@ -338,29 +374,27 @@ public class MainActivity extends AppCompatActivity {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(keyStartStop, start);
editor.putBoolean(keyAppOpen, true);
editor.putBoolean(keyServiceRunning, false);
editor.apply();
// hours:minutes:seconds should be disabled during count down.
flipInputTexts();
if (buttonText.equals(getString(R.string.btnStart))){
incrementTime.sendEmptyMessage(0);
setLoopInterval();
resetTimeLeft();
setStartTime();
// Start the background alert service using Alert manager
long interval = longLoopInterval > 1000 ? longLoopInterval : 60000; // Minimum 1 minute interval for alarms
if (Alert.isExactAlarmAllowed(this)) {
Alert.start(this, interval);
if (DEBUG) Log.d(tag, "Starting ForegroundService with interval: " + interval);
// Delegate countdown logic to ForegroundService to survive Doze mode on SDK 36+
Intent svcIntent = new Intent(this, TimerForegroundService.class);
svcIntent.setAction(Alert.ACTION_TIMER);
// Pass the calculated `interval` (which includes the 60s fallback if user entered nothing)
svcIntent.putExtra(TimerForegroundService.EXTRA_INTERVAL_MS, interval);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(svcIntent);
} else {
if (DEBUG) Log.w(tag, "Cannot start alert: Exact alarm permission denied.");
new AlertDialog.Builder(MainActivity.this)
.setTitle("Permission Required")
.setMessage("Please grant 'All files access' or 'Alarm' permissions in system settings for this feature to work.")
.setPositiveButton("OK", (d, w) -> d.dismiss())
.show();
startService(svcIntent);
}
}
@@ -371,13 +405,11 @@ public class MainActivity extends AppCompatActivity {
etMinutes.setEnabled(false);
etSeconds.setEnabled(false);
}
else if (buttonText.equals(getString(R.string.btnStop))){
setChronometer(longLoopInterval);
}
else if (buttonText.equals(getString(R.string.btnResume))){
setStartTime();
incrementTime.sendEmptyMessage(0);
btnResetPause.setEnabled(true);
else if (buttonText.equals(getString(R.string.btnStop)) || buttonText.equals(getString(R.string.btnResume))){
// Stop the Foreground Service and cancel alarms
Intent svcIntent = new Intent(this, TimerForegroundService.class);
stopService(svcIntent);
Alert.stop(this);
}
flipStartStopButton();
@@ -474,79 +506,7 @@ public class MainActivity extends AppCompatActivity {
if (DEBUG) Log.d(tag, "Finished");
}
private final Handler incrementTime = new Handler(){
@Override
public void handleMessage(Message msg) {
String tag = TAG + "handleMessage";
if (DEBUG) Log.d(tag, "Starting");
super.handleMessage(msg);
appOpen = sharedPreferences.getBoolean(keyAppOpen, true);
if (appOpen) {
sharedPreferences.edit().putBoolean(keyServiceRunning, false).apply();
} else {
sharedPreferences.edit().putBoolean(keyServiceRunning, true).apply();
}
start = sharedPreferences.getBoolean(keyStartStop, false);
if (start){
//start = !start;
//sharedPreferences.edit().putBoolean(keyStartStop, false).apply();
// Calculate new time and text
setTimeLeft();
if (DEBUG) Log.d(tag, "longTimeLeft=" + longTimeLeft);
// Check if we need to beep
if (longTimeLeft < 1000){
playSound();
resetTimeLeft();
setStartTime();
if (DEBUG) {
Log.d(tag, "longLoopInterval=" + longLoopInterval);
Log.d(tag, "longStartTime=" + longStartTime);
Log.d(tag, "longEndTime=" + longEndTime);
Log.d(tag, "longTimeLeft=" + longTimeLeft);
Log.d(tag, "waitInterval=" + waitInterval);
Log.d(tag, "start=" + start);
//chronometer.setText("Test");
//setChronometer(200);
/*
start=false;
startStopChronometer("Start");
*/
}
}
// Wait
Runnable task = new Runnable() {
@Override
public void run() {
synchronized (this){
try{
wait(waitInterval);
if (DEBUG) Log.d(tag, "Done waiting.");
}
catch (Exception e){
e.printStackTrace();
if (DEBUG) Log.d(tag, "Failed to wait.");
}
}
//sharedPreferences.edit().putBoolean(keyStartStop, true).apply();
incrementTime.sendEmptyMessage(0);
//startStopChronometer("Start");
}
};
Thread t = new Thread(task);
t.start();
}
if (DEBUG) Log.d(tag, "Finished");
}
};
// Removed local countdown Handler - timing and background survival is now delegated to TimerForegroundService
private void setStartTime(){
String tag = TAG + "setStartTime";
@@ -597,17 +557,34 @@ public class MainActivity extends AppCompatActivity {
if (DEBUG) Log.d(tag, "Starting");
try {
// Safely instantiate MediaPlayer locally to prevent NPE
Uri uri = android.media.RingtoneManager.getDefaultUri(android.media.RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer localPlayer = MediaPlayer.create(this, uri);
// Stop any existing notification ringtone first to prevent overlap
if (notificationRingtone != null && notificationRingtone.isPlaying()) {
notificationRingtone.stop();
}
// Use RingtoneManager which handles async playback lifecycle properly
Uri uri = android.media.RingtoneManager.getDefaultUri(android.media.RingtoneManager.TYPE_NOTIFICATION);
notificationRingtone = android.media.RingtoneManager.getRingtone(this, uri);
if (notificationRingtone != null) {
// Ringtone.play() is asynchronous and handles its own lifecycle,
// avoiding the MediaPlayer.create() + immediate release bug that
// caused silence on subsequent loops
notificationRingtone.play();
} else {
// Fallback: if getRingtone fails, try direct MediaPlayer with proper lifecycle
MediaPlayer localPlayer = MediaPlayer.create(this, uri);
if (localPlayer != null) {
localPlayer.start();
localPlayer.release(); // Clean up resources immediately
} else {
// Fallback for edge cases where create() fails
android.media.Ringtone ringtone = android.media.RingtoneManager.getRingtone(this, uri);
if (ringtone != null) ringtone.play();
final MediaPlayer fp = localPlayer;
// Release after playback completes (use delay as a safety net)
new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(
new Runnable() { @Override public void run() {
if (fp.isPlaying()) fp.stop();
fp.release();
}}, 2000
);
}
}
} catch (Exception e) {
sharedPreferences.edit().putBoolean(keyStartStop, false).apply();
@@ -694,6 +671,8 @@ public class MainActivity extends AppCompatActivity {
String tag = TAG + "onPause";
if (DEBUG) Log.d(tag, "Starting");
unregisterReceiver(timerUpdateReceiver);
stringLoopInterval =
etHours.getText().toString() + ":" +
etMinutes.getText().toString() + ":" +
@@ -724,6 +703,14 @@ public class MainActivity extends AppCompatActivity {
recoverScreen();
syncVolume();
// Register receiver to get live updates from ForegroundService while app is visible
IntentFilter filter = new IntentFilter(TimerForegroundService.class.getName() + ".UPDATE");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
registerReceiver(timerUpdateReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
} else {
registerReceiver(timerUpdateReceiver, filter);
}
if (DEBUG) Log.d(tag, "Finished");
}
@@ -734,6 +721,12 @@ public class MainActivity extends AppCompatActivity {
// Stop the background alert service when destroying activity
Alert.stop(this);
if (mediaPlayer != null) { mediaPlayer.release(); mediaPlayer = null; }
// Clean up ringtone player to prevent resource leak across config changes
if (notificationRingtone != null && notificationRingtone.isPlaying()) {
notificationRingtone.stop();
}
if (DEBUG) Log.d(tag, "Done with local code, calling super..");
@@ -4,46 +4,80 @@ import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class TimerForegroundService extends Service {
private static final String TAG = "TimerFGService";
private static final String CHANNEL_ID = "timer_notification_channel";
private static final int NOTIFICATION_ID = 1001;
public static final String CHANNEL_ID = "timer_notification_channel";
public static final int NOTIFICATION_ID = 1001;
// Intent extras to start the timer
public static final String EXTRA_INTERVAL_MS = "com.hyperling.apps.infinitetimer.INTERVAL_MS";
private PowerManager.WakeLock wakeLock;
private MediaPlayer mediaPlayer;
private Handler serviceHandler;
// Timer state
private long loopIntervalMs;
private long endTimeMillis;
private Ringtone ringtonePlayer;
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
// Android 8+ requires foreground service to play sound reliably while backgrounded
startForeground(NOTIFICATION_ID, buildNotification());
// Acquire PARTIAL_WAKE_LOCK to keep CPU awake during Doze mode
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TimerWakeLock");
// Lock for up to 60 seconds to ensure audio finishes playing even if CPU sleeps
wakeLock.acquire(60 * 1000L);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "InfiniteTimer:TimerFGWakeLock");
playSound();
// Use main looper for safe UI updates from foreground service
serviceHandler = new Handler(Looper.getMainLooper());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY; // Don't restart immediately if killed
if (intent == null || !Alert.ACTION_TIMER.equals(intent.getAction())) {
return START_NOT_STICKY;
}
// Start persistent foreground notification immediately to prevent Doze mode killing us
startForeground(NOTIFICATION_ID, buildNotification("Timer is active..."));
// Acquire wake lock briefly on start, but we'll hold it continuously as long as service runs
if (!wakeLock.isHeld()) {
wakeLock.acquire();
}
// If interval is passed via intent (first start), set it up.
// Otherwise, rely on AlarmManager/Handler to keep running.
long newInterval = intent.getLongExtra(EXTRA_INTERVAL_MS, -1);
if (newInterval > 0) {
loopIntervalMs = newInterval;
endTimeMillis = System.currentTimeMillis() + loopIntervalMs;
tick(); // Start the countdown immediately when the service is launched
} else {
Log.w(TAG, "Received start command without a valid positive interval.");
}
return START_STICKY;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Timer Notifications", NotificationManager.IMPORTANCE_HIGH);
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, "Timer Notifications",
NotificationManager.IMPORTANCE_HIGH
);
// Disable default sound to avoid double-sound on some OEMs
channel.setSound(null, null);
channel.enableVibration(false);
@@ -52,44 +86,103 @@ public class TimerForegroundService extends Service {
}
}
private android.app.Notification buildNotification() {
private android.app.Notification buildNotification(String textContent) {
return new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Infinite Timer")
.setContentText("Timer is active...")
// Use system alarm icon temporarily. Add your own ic_stat_notification if desired
.setContentText(textContent)
.setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOngoing(true)
.setStyle(new NotificationCompat.InboxStyle().addLine(textContent))
.build();
}
private void playSound() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) return;
// --- Core Timer Engine ---
/**
* Starts or resumes the countdown engine.
* Foreground services bypass Doze mode restrictions, allowing this to run reliably on SDK 36+.
*/
public void startTimer(long intervalMs) {
if (loopIntervalMs == intervalMs && serviceHandler.hasMessages(0)) {
return; // Already running at this interval
}
loopIntervalMs = intervalMs;
endTimeMillis = System.currentTimeMillis() + loopIntervalMs;
tick();
}
public void stopTimer() {
if (serviceHandler != null) {
serviceHandler.removeCallbacksAndMessages(null);
if (wakeLock.isHeld()) wakeLock.release();
}
}
private void tick() {
long currentTime = System.currentTimeMillis();
long remainingMs = endTimeMillis - currentTime;
if (remainingMs <= 0) {
playAlarmSound();
// Loop indefinitely: reschedule for the next interval
endTimeMillis += loopIntervalMs;
remainingMs = loopIntervalMs;
}
String timeStr = formatTime(remainingMs);
updateNotification(timeStr);
// Send local broadcast to MainActivity so UI updates live while app is visible
Intent broadcast = new Intent(TimerForegroundService.class.getName() + ".UPDATE");
broadcast.putExtra("remainingTime", timeStr);
sendBroadcast(broadcast);
// Schedule next tick immediately (foreground service allows high-frequency updates)
serviceHandler.postDelayed(tickRunnable, 500);
}
private final Runnable tickRunnable = new Runnable() {
@Override
public void run() { tick(); }
};
private void playAlarmSound() {
try {
// Plays default notification sound. Replace with R.raw.your_sound if you want custom audio
// Stop any previous ringtone to prevent overlap
if (ringtonePlayer != null && ringtonePlayer.isPlaying()) {
ringtonePlayer.stop();
}
Uri uri = android.media.RingtoneManager.getDefaultUri(android.media.RingtoneManager.TYPE_NOTIFICATION);
mediaPlayer = MediaPlayer.create(this, uri);
if (mediaPlayer != null) {
mediaPlayer.setOnCompletionListener(mp -> stopSelf()); // Stop immediately after playing
mediaPlayer.start();
} else {
stopSelf(); // Fallback if media player fails
}
ringtonePlayer = android.media.RingtoneManager.getRingtone(this, uri);
if (ringtonePlayer != null) ringtonePlayer.play();
} catch (Exception e) {
Log.e(TAG, "Failed to play sound", e);
stopSelf();
Log.e(TAG, "Failed to play alarm sound", e);
}
}
private void updateNotification(String timeStr) {
NotificationManager nm = getSystemService(NotificationManager.class);
if (nm != null) {
nm.notify(NOTIFICATION_ID, buildNotification(timeStr));
}
}
private String formatTime(long ms) {
long totalSeconds = ms / 1000;
long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60;
return String.format("%02d:%02d", minutes, seconds);
}
@Override
public IBinder onBind(Intent intent) { return null; }
@Override
public void onDestroy() {
super.onDestroy();
if (wakeLock.isHeld()) wakeLock.release();
if (mediaPlayer != null) { mediaPlayer.release(); mediaPlayer = null; }
stopTimer();
if (ringtonePlayer != null && ringtonePlayer.isPlaying()) ringtonePlayer.stop();
Log.d(TAG, "Service destroyed.");
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ buildscript {
}
}
dependencies {
classpath 'com.android.tools.build:gradle:9.4.1'
classpath 'com.android.tools.build:gradle:9.5.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
+1 -1
View File
@@ -1,6 +1,6 @@
#Fri Jul 11 12:55:34 MST 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists