Search code examples
androideventscallbackmedia-player

Android MediaPlayer On Stop Event, or similar, exists?


I have several activities which use several audio features. For that, I have a MediaPlayer in a singleton java class, so the activities interact with that class and just exist on the media player.

One of the features is to stop automatically the media player after X minutes. So I created a timer in the singleton class and stops perfectly the radio streaming. the problem is that there is no feedback or callback to the running activity. There is a play/stop button wich has to change the image and I do not know how can I capture that onStop event or whatever....or can be called from a single java class the current activity class running, so I could call a function of the activity in order to change the image?


Solution

  • You probably want to use a broadcast receiver for this.

    From your singlton class which does the stopping, when your timer stops the music, call this method:

    public void broadcastMusicPaused(View v){
        Intent broadcast = new Intent();
        broadcast.setAction("MUSIC_STOPPED");
        sendBroadcast(broadcast);
    }
    

    Then, from your controlling activity, set up your receiver like this:

    private BroadcastReceiver receiver = new BroadcastReceiver() {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "Music Paused", Toast.LENGTH_SHORT).show();
            displayMusicStopped();       //switches images
        }
    };
    
    @Override
    protected void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("MUSIC_STOPPED");
        registerReceiver(receiver, filter);
    
        super.onResume();
    }
    
    @Override
    protected void onPause() {
        unregisterReceiver(receiver);
        super.onPause();
    }