Skip to content Skip to sidebar Skip to footer

Android Mediaplayer - Play Ringtone One Time

I try to play a device ringtone one time with the MediaPlayer class (I have to use MediaPlayer as I use the ringtones together with other audio sources in my app) So i try the foll

Solution 1:

I found simple solution with use events - confirm answer since it solves your problem :)

mediaPlayer.setOnSeekCompleteListener(newMediaPlayer.OnSeekCompleteListener() {
                    @OverridepublicvoidonSeekComplete(MediaPlayer mediaPlayer) {
                        mediaPlayer.stop();
                    }
                });

http://developer.android.com/reference/android/media/MediaPlayer.html

Remember about release().

            mediaPlayer.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
                @OverridepublicvoidonCompletion(MediaPlayer mediaPlayer) {
                    mediaPlayer.release();
                }
            });

Full code it your want to use need set ring tone to something what you would like.

AudioManageraudioManager= (AudioManager)getSystemService(AUDIO_SERVICE);
        intvolume= audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
        SharedPreferencesprefs= PreferenceManager.getDefaultSharedPreferences(view.getContext());
        UrinotificationSoundUri= Uri.parse(prefs.getString("notification_sound", "DEFAULT_SOUND"));

        MediaPlayermediaPlayer=newMediaPlayer();
        try {
            mediaPlayer.setDataSource(view.getContext(), notificationSoundUri);
        } catch (Exception e1) {
            e1.printStackTrace();
            mediaPlayer.release();
            return;
        }
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
        mediaPlayer.setOnCompletionListener(newMediaPlayer.OnCompletionListener() {
            @OverridepublicvoidonCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.release();
            }
        });
        try {
            mediaPlayer.prepare();
        } catch (Exception e1) {
            e1.printStackTrace();
            mediaPlayer.release();
            return;
        }
        mediaPlayer.setOnSeekCompleteListener(newMediaPlayer.OnSeekCompleteListener() {

            @OverridepublicvoidonSeekComplete(MediaPlayer mediaPlayer) {
                // TODO Auto-generated method stub
                mediaPlayer.stop();
                mediaPlayer.start();
            }
        });
        mediaPlayer.setVolume(volume, volume);
        mediaPlayer.start();

Solution 2:

use Notifications

NotificationManagernManager= 
           (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);    
   NotificationCompat.BuildernotifBuilder=newNotificationCompat.Builder(context);
   notifBuilder.setSound(sound);
   notification = notifBuilder.build();

   nManager.notify(SOME_INT_CONSTANT, notification);

Post a Comment for "Android Mediaplayer - Play Ringtone One Time"