简体   繁体   English

停止来自活动android的媒体播放器(从广播接收器启动)

[英]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. 我有一个AlarmManager通知广播接收器,广播接收器使用MediaPlayer类播放一个Rigntone。 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);
}

I am also came across with the same problem. 我也遇到同样的问题。 i solved it.Create a service class and declare the media player in that class. 我解决了它。创建一个服务类并在该类中声明媒体播放器。 once the alarm fires, start the service class from broadcast receiver class and stop the service from any activity. 警报触发后,请从广播接收器类启动服务类,并停止任何活动。 hope so it helpful. 希望对您有所帮助。

In broadcast receiver class 广播接收器类中

Intent serviceIntent = new Intent(context,MyService.class);
            context.startService(serviceIntent);

from any of activity 来自任何活动

stopService(new Intent (getApplicationContext(),MyService.class));

Guys you can save mediaplayer instance in application class and access it from anywhere. 伙计们,您可以将mediaplayer实例保存在应用程序类中,然后从任何地方访问它。 This will help you: How to declare global variables in Android? 这将对您帮助: 如何在Android中声明全局变量?

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. 由于您正在开始一项活动,因此,请让它播放铃声。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM