关闭Android中播放音乐的所有服务

时间:2013-07-06 03:15:33

标签: android android-activity

我使用闹钟管理器停止所有音乐在Android中播放。但我不知道这是怎么回事。 在主要活动源代码

 Intent intent = new Intent(AlarmActivity.this, OneShotAlarm.class);
        PendingIntent sender = PendingIntent.getBroadcast(AlarmActivity.this,
                0, intent, 0);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, 5);

        // Schedule the alarm!
        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

和警报扩展了BroadcastReceiver

public class OneShotAlarm extends BroadcastReceiver

{

@Override
public void onReceive(Context context, Intent intent)
{  
// What can I do for stop music of device is running
    Toast.makeText(context, R.string.one_shot_received, Toast.LENGTH_SHORT).show();
}

}

1 个答案:

答案 0 :(得分:0)

您可以查看:AudioManager

这样的事情应该有效:

AudioManager aManager = (AudioManager)getSystemService(AUDIO_SERVICE);
aManager.setStreamMute(AudioManager.STREAM_MUSIC, true);

编辑: 有一个功能可以采用“音频聚焦”:AudioManager

public int requestAudioFocus (AudioManager.OnAudioFocusChangeListener l, int streamType, int durationHint)

Sample

AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
...

// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
                                 // Use the music stream.
                                 AudioManager.STREAM_MUSIC,
                                 // Request permanent focus.
                                 AudioManager.AUDIOFOCUS_GAIN);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
    // Start playback.
}