从活动android停止媒体播放器(从广播接收器发起)

时间:2011-05-08 16:48:04

标签: java android media-player

我有一个AlarmManager通知广播接收器,广播接收器使用MediaPlayer类播放一个严格的行为。当警报触发时,我有一个启动的活动,并有一个OK按钮,应该停止媒体播放器。问题是如何从活动中访问媒体播放器,以便我可以阻止它。

我的代码如下:

    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);
}

3 个答案:

答案 0 :(得分:2)

我也遇到了同样的问题。我解决了它。创建一个服务类并在该类中声明媒体播放器。一旦警报触发,从广播接收器类启动服务类并停止任何活动的服务。希望如此有用。

广播接收器

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

来自任何活动

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

答案 1 :(得分:1)

  

问题是如何从活动中访问媒体播放器,以便我可以阻止它。

你做不到。你泄露了它。因为你正在开始一项活动,无论如何,让它播放铃声。

答案 2 :(得分:1)

您可以将媒体播放器实例保存在应用程序类中,并从任何地方访问它。 这将对您有所帮助:How to declare global variables in Android?