How do I stop the currently playing ringtone?

前端 未结 3 561
野趣味
野趣味 2021-02-02 02:38

I\'m writing an app that sometime fires reminders that are supposed to play ringtones. I can start the ringtone OK, but can\'t stop it. I have a dismiss method in my fragment th

3条回答
  •  情话喂你
    2021-02-02 03:40

    You have to create a class extending from Service class, the demo code is given below

    Please Note this is the code form my College Project, it is for starting up default Alarm using Ringtone from BroadcastReciever extending Activity and Stopping the Ringtone from different normal Android Activity.

    Service Class code:

    import android.app.Service;
    import android.content.Intent;
    import android.media.Ringtone;
    import android.media.RingtoneManager;
    import android.net.Uri;
    import android.os.IBinder;
    public class AlarmRing extends Service {
    static Ringtone r;
    
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        //activating alarm sound
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        r = RingtoneManager.getRingtone(getBaseContext(), notification);
        //playing sound alarm
        r.play();
    
        return START_NOT_STICKY;
    }
    @Override
    public void onDestroy()
    {
        r.stop();
    }
    }
    

    Code for Activity calling the Service:

    Intent i = new Intent(context, AlarmRing.class);
    context.startService(i);
    

    Activity ending or closing the Service:

    Intent i = new Intent(this, AlarmRing.class);
    stopService(i);`
    

    NOTE: please note for context reference.

提交回复
热议问题