Search code examples
androidalarmmanagerandroid-pendingintent

Can't stop the ringing alarm from another activity


I am new to android ,Here I am practicing my first app (Alarm App).

I have an issue in my app that I can't stop the alarm once a alarm is triggered it's keep on ringing can't get stopped.

In my app I have 2 activities and a AlarmReceiver .

From the AlarmActivity.java I have set the alarm ,when the specific time is reached the Alarmreceiver.java will get triggered and the alarm started to ring and showing a wakeup screen .

From the WakeUpScreen.java I have a stop button by using that I need to stop the current ringing alarm .

I don't have any issues in logcat too.

AlarmActivity.java

  public void stopAlarm(Context context) {
        Intent intent = new Intent(context,AlarmReceiver.class);
        intent.setAction("ALARM_OFF");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, mAlarmId, intent,PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);
    }

I have this AlarmStop() function in my AlarmActivity.java which will get hit when I press the stop button in wakeupscreen.java

When I am try to debug the stop process the debugger moved all the lines in the stopAlarm() function but the Intent is not worked that's why the AlarmReceiver.java file is not get called ,I mean,The debugger moved all the lines in the aboved method but the AlarmReceiver.java is not get called

I tried lot of ways to solve this but I missed something that I can't figured it out.

Can anyone help me to stop the triggered alarm and it's ringing sound .


Solution

  • Your architecture is broken. You don't use a BroadcastReceiver for persistent processing. A BroadcastReceiver has a very short lifecycle, you use it to trigger other things.

    You've created a MediaPlayer instance in your BroadcastReceiver and are trying to control that in onReceive(). This is wrong. You should use a Service to manage and maintain the state of your MediaPlayer.

    See if you can find some HOWTO guides on the Internet for how to build such an application.