Search code examples
javaandroidmedia-player

Stop media player (initiated from a broadcast receiver ) from an activity android


I have an AlarmManager that notifies a broadcast receiver and the broadcast receiver plays a rigntone using the MediaPlayer class. when The alarm fires I have an activity that launches and have an OK button that should stop the media player. the question is how can I access the media player from the activity so I can stop it.

my code is as follow:

    public void onReceive(Context context, Intent intent) {
    // some other code........          
        try
        {
            MediaPlayer mediaPlayer = playAlarm(context, fileName);
            createAlarmNotificationDialog(context, mediaPlayer);
        }
        catch ( Exception ex)
        {
            ex.printStackTrace();
        }
    }

}

private MediaPlayer playAlarm(Context context, String fileName) throws IllegalStateException, IOException
{

    File inputFile = new File("/sdcard/sampleringtone.mp3");

    //File inputFile = new File("/system/media/audio/alarms/" + fileName + ".mp3");
    FileInputStream fis = new FileInputStream(inputFile);

    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setDataSource(fis.getFD());
    //mediaPlayer.setLooping(true);
    mediaPlayer.prepare();
    mediaPlayer.start();
    return mediaPlayer;
}

private void createAlarmNotificationDialog(Context context, final MediaPlayer mediaPlayer)
{
    Intent intent = new Intent(context, AlarmNotificationActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

Solution

  • the question is how can I access the media player from the activity so I can stop it.

    You can't. You leaked it. Since you are starting an activity, anyway, have it play the ringtone.