开发者

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

开发者 https://www.devze.com 2023-03-03 23:08 出处:网络
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

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 mediaPlay开发者_开发技巧er;
}

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


Guys you can save mediaplayer instance in application class and access it from anywhere. This will help you: How to declare global variables in Android?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消