List of usage examples for android.content Intent ACTION_MEDIA_BUTTON
String ACTION_MEDIA_BUTTON
To view the source code for android.content Intent ACTION_MEDIA_BUTTON.
Click Source Link
From source file:com.example.android.mediarouter.player.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { // Be sure to call the super class. super.onCreate(savedInstanceState); if (savedInstanceState != null) { mPlayer = (Player) savedInstanceState.getSerializable("mPlayer"); }//www . ja va 2 s . co m // Get the media router service. mMediaRouter = MediaRouter.getInstance(this); // Create a route selector for the type of routes that we care about. mSelector = new MediaRouteSelector.Builder().addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO) .addControlCategory(MediaControlIntent.CATEGORY_LIVE_VIDEO) .addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK) .addControlCategory(SampleMediaRouteProvider.CATEGORY_SAMPLE_ROUTE).build(); // Add a fragment to take care of media route discovery. // This fragment automatically adds or removes a callback whenever the activity // is started or stopped. FragmentManager fm = getSupportFragmentManager(); DiscoveryFragment fragment = (DiscoveryFragment) fm.findFragmentByTag(DISCOVERY_FRAGMENT_TAG); if (fragment == null) { fragment = new DiscoveryFragment(mMediaRouterCB); fragment.setRouteSelector(mSelector); fm.beginTransaction().add(fragment, DISCOVERY_FRAGMENT_TAG).commit(); } else { fragment.setCallback(mMediaRouterCB); fragment.setRouteSelector(mSelector); } // Populate an array adapter with streaming media items. String[] mediaNames = getResources().getStringArray(R.array.media_names); String[] mediaUris = getResources().getStringArray(R.array.media_uris); mLibraryItems = new LibraryAdapter(); for (int i = 0; i < mediaNames.length; i++) { mLibraryItems.add(new MediaItem("[streaming] " + mediaNames[i], Uri.parse(mediaUris[i]), "video/mp4")); } // Scan local external storage directory for media files. File externalDir = Environment.getExternalStorageDirectory(); if (externalDir != null) { File list[] = externalDir.listFiles(); if (list != null) { for (int i = 0; i < list.length; i++) { String filename = list[i].getName(); if (filename.matches(".*\\.(m4v|mp4)")) { mLibraryItems.add(new MediaItem("[local] " + filename, Uri.fromFile(list[i]), "video/mp4")); } } } } mPlayListItems = new PlaylistAdapter(); // Initialize the layout. setContentView(R.layout.sample_media_router); TabHost tabHost = (TabHost) findViewById(R.id.tabHost); tabHost.setup(); String tabName = getResources().getString(R.string.library_tab_text); TabSpec spec1 = tabHost.newTabSpec(tabName); spec1.setContent(R.id.tab1); spec1.setIndicator(tabName); tabName = getResources().getString(R.string.playlist_tab_text); TabSpec spec2 = tabHost.newTabSpec(tabName); spec2.setIndicator(tabName); spec2.setContent(R.id.tab2); tabName = getResources().getString(R.string.statistics_tab_text); TabSpec spec3 = tabHost.newTabSpec(tabName); spec3.setIndicator(tabName); spec3.setContent(R.id.tab3); tabHost.addTab(spec1); tabHost.addTab(spec2); tabHost.addTab(spec3); tabHost.setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String arg0) { updateUi(); } }); mLibraryView = (ListView) findViewById(R.id.media); mLibraryView.setAdapter(mLibraryItems); mLibraryView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); mLibraryView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { updateButtons(); } }); mPlayListView = (ListView) findViewById(R.id.playlist); mPlayListView.setAdapter(mPlayListItems); mPlayListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); mPlayListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { updateButtons(); } }); mInfoTextView = (TextView) findViewById(R.id.info); mPauseResumeButton = (ImageButton) findViewById(R.id.pause_resume_button); mPauseResumeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mPaused = !mPaused; if (mPaused) { mSessionManager.pause(); } else { mSessionManager.resume(); } } }); mStopButton = (ImageButton) findViewById(R.id.stop_button); mStopButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mPaused = false; mSessionManager.stop(); } }); mSeekBar = (SeekBar) findViewById(R.id.seekbar); mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { PlaylistItem item = getCheckedPlaylistItem(); if (fromUser && item != null && item.getDuration() > 0) { long pos = progress * item.getDuration() / 100; mSessionManager.seek(item.getItemId(), pos); item.setPosition(pos); item.setTimestamp(SystemClock.elapsedRealtime()); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { mSeeking = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { mSeeking = false; updateUi(); } }); // Schedule Ui update mHandler.postDelayed(mUpdateSeekRunnable, 1000); // Build the PendingIntent for the remote control client mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mEventReceiver = new ComponentName(getPackageName(), SampleMediaButtonReceiver.class.getName()); Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.setComponent(mEventReceiver); mMediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0); // Create and register the remote control client registerRemoteControlClient(); // Set up playback manager and player mPlayer = Player.create(MainActivity.this, mMediaRouter.getSelectedRoute()); mSessionManager.setPlayer(mPlayer); mSessionManager.setCallback(new SessionManager.Callback() { @Override public void onStatusChanged() { updateUi(); } @Override public void onItemChanged(PlaylistItem item) { } }); updateUi(); }
From source file:com.example.android.mediarouter.player.RadioActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { // Be sure to call the super class. super.onCreate(savedInstanceState); if (savedInstanceState != null) { mPlayer = (RadioPlayer) savedInstanceState.getSerializable("mPlayer"); }//from w w w.j a va 2 s. co m // Get the media router service. mMediaRouter = MediaRouter.getInstance(this); // Create a route selector for the type of routes that we care about. mSelector = new MediaRouteSelector.Builder().addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO) .addControlCategory(MediaControlIntent.CATEGORY_LIVE_VIDEO) .addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK) .addControlCategory(SampleMediaRouteProvider.CATEGORY_SAMPLE_ROUTE).build(); // Add a fragment to take care of media route discovery. // This fragment automatically adds or removes a callback whenever the activity // is started or stopped. FragmentManager fm = getSupportFragmentManager(); DiscoveryFragment fragment = (DiscoveryFragment) fm.findFragmentByTag(DISCOVERY_FRAGMENT_TAG); if (fragment == null) { fragment = new DiscoveryFragment(mMediaRouterCB); fragment.setRouteSelector(mSelector); fm.beginTransaction().add(fragment, DISCOVERY_FRAGMENT_TAG).commit(); } else { fragment.setCallback(mMediaRouterCB); fragment.setRouteSelector(mSelector); } // Populate an array adapter with streaming media items. String[] mediaNames = getResources().getStringArray(R.array.media_names); String[] mediaUris = getResources().getStringArray(R.array.media_uris); mLibraryItems = new LibraryAdapter(); for (int i = 0; i < mediaNames.length; i++) { mLibraryItems.add(new MediaItem("[streaming] " + mediaNames[i], Uri.parse(mediaUris[i]), "video/mp4")); } // Scan local external storage directory for media files. File externalDir = Environment.getExternalStorageDirectory(); if (externalDir != null) { File list[] = externalDir.listFiles(); if (list != null) { for (int i = 0; i < list.length; i++) { String filename = list[i].getName(); if (filename.matches(".*\\.(m4v|mp4)")) { mLibraryItems.add(new MediaItem("[local] " + filename, Uri.fromFile(list[i]), "video/mp4")); } } } } mPlayListItems = new PlaylistAdapter(); // Initialize the layout. setContentView(R.layout.sample_radio_router); TabHost tabHost = (TabHost) findViewById(R.id.tabHost); tabHost.setup(); String tabName = getResources().getString(R.string.library_tab_text); TabSpec spec1 = tabHost.newTabSpec(tabName); spec1.setContent(R.id.tab1); spec1.setIndicator(tabName); tabName = getResources().getString(R.string.playlist_tab_text); TabSpec spec2 = tabHost.newTabSpec(tabName); spec2.setIndicator(tabName); spec2.setContent(R.id.tab2); tabName = getResources().getString(R.string.statistics_tab_text); TabSpec spec3 = tabHost.newTabSpec(tabName); spec3.setIndicator(tabName); spec3.setContent(R.id.tab3); tabHost.addTab(spec1); tabHost.addTab(spec2); tabHost.addTab(spec3); tabHost.setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String arg0) { updateUi(); } }); mLibraryView = (ListView) findViewById(R.id.media); mLibraryView.setAdapter(mLibraryItems); mLibraryView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); mLibraryView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { updateButtons(); } }); mPlayListView = (ListView) findViewById(R.id.playlist); mPlayListView.setAdapter(mPlayListItems); mPlayListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); mPlayListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { updateButtons(); } }); mInfoTextView = (TextView) findViewById(R.id.info); mPauseResumeButton = (ImageButton) findViewById(R.id.pause_resume_button); mPauseResumeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mPaused = !mPaused; if (mPaused) { mSessionManager.pause(); } else { mSessionManager.resume(); } } }); mStopButton = (ImageButton) findViewById(R.id.stop_button); mStopButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mPaused = false; mSessionManager.stop(); } }); mSeekBar = (SeekBar) findViewById(R.id.seekbar); mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { PlaylistItem item = getCheckedPlaylistItem(); if (fromUser && item != null && item.getDuration() > 0) { long pos = progress * item.getDuration() / 100; mSessionManager.seek(item.getItemId(), pos); item.setPosition(pos); item.setTimestamp(SystemClock.elapsedRealtime()); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { mSeeking = true; } @Override public void onStopTrackingTouch(SeekBar seekBar) { mSeeking = false; updateUi(); } }); // Schedule Ui update mHandler.postDelayed(mUpdateSeekRunnable, 1000); // Build the PendingIntent for the remote control client mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mEventReceiver = new ComponentName(getPackageName(), SampleMediaButtonReceiver.class.getName()); Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.setComponent(mEventReceiver); mMediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0); // Create and register the remote control client registerRemoteControlClient(); // Set up playback manager and player mPlayer = RadioPlayer.create(RadioActivity.this, mMediaRouter.getSelectedRoute()); mSessionManager.setPlayer(mPlayer); mSessionManager.setCallback(new RadioSessionManager.Callback() { @Override public void onStatusChanged() { updateUi(); } @Override public void onItemChanged(PlaylistItem item) { } }); updateUi(); }
From source file:br.com.viniciuscr.notification2android.mediaPlayer.MediaPlaybackService.java
@Override public void onCreate() { super.onCreate(); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); ComponentName rec = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()); mAudioManager.registerMediaButtonEventReceiver(rec); Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON); i.setComponent(rec);/*from w w w . j a v a 2 s .c o m*/ PendingIntent pi = PendingIntent.getBroadcast(this /*context*/, 0 /*requestCode, ignored*/, i /*intent*/, 0 /*flags*/); mRemoteControlClient = new RemoteControlClient(pi); mAudioManager.registerRemoteControlClient(mRemoteControlClient); int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP; mRemoteControlClient.setTransportControlFlags(flags); mPreferences = getSharedPreferences("Music", MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE); mCardId = MusicUtils.getCardId(this); registerExternalStorageListener(); // Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes. mPlayer = new MultiPlayer(); mPlayer.setHandler(mMediaplayerHandler); reloadQueue(); notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); IntentFilter commandFilter = new IntentFilter(); commandFilter.addAction(SERVICECMD); commandFilter.addAction(TOGGLEPAUSE_ACTION); commandFilter.addAction(PAUSE_ACTION); commandFilter.addAction(NEXT_ACTION); commandFilter.addAction(PREVIOUS_ACTION); registerReceiver(mIntentReceiver, commandFilter); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName()); mWakeLock.setReferenceCounted(false); // If the service was idle, but got killed before it stopped itself, the // system will relaunch it. Make sure it gets stopped again in that case. Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); }
From source file:be.ugent.zeus.hydra.util.audiostream.MusicService.java
/** * Starts playing the next song. If manualUrl is null, the next song will be randomly selected * from our Media Retriever (that is, it will be a random song in the user's device). If * manualUrl is non-null, then it specifies the URL or path to the song that will be played * next.// w ww .ja v a 2s. c o m */ void playmp3(String mp3url) { mState = State.Stopped; relaxResources(false); // release everything except MediaPlayer try { // set the source of the media player to a manual URL or path createMediaPlayerIfNeeded(); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.setDataSource(mp3url); mIsStreaming = true; mSongTitle = "Urgent.fm"; mState = State.Preparing; setUpAsForeground(mSongTitle + " (loading)"); // Use the media button APIs (if available) to register ourselves for media button // events MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, mMediaButtonReceiverComponent); // Use the remote control APIs (if available) to set the playback state if (mRemoteControlClientCompat == null) { Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON); intent.setComponent(mMediaButtonReceiverComponent); mRemoteControlClientCompat = new RemoteControlClientCompat(PendingIntent.getBroadcast( this /*context*/, 0 /*requestCode, ignored*/, intent /*intent*/, 0 /*flags*/)); RemoteControlHelper.registerRemoteControlClient(mAudioManager, mRemoteControlClientCompat); } mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING); mRemoteControlClientCompat.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP); // Update the remote controls mRemoteControlClientCompat.editMetadata(true) .putString(MediaMetadataRetriever.METADATA_KEY_TITLE, "Urgent.fm") .putBitmap(RemoteControlClientCompat.MetadataEditorCompat.METADATA_KEY_ARTWORK, mDummyAlbumArt) .apply(); // starts preparing the media player in the background. When it's done, it will call // our OnPreparedListener (that is, the onPrepared() method on this class, since we set // the listener to 'this'). // // Until the media player is prepared, we *cannot* call start() on it! mPlayer.prepareAsync(); // If we are streaming from the internet, we want to hold a Wifi lock, which prevents // the Wifi radio from going to sleep while the song is playing. If, on the other hand, // we are *not* streaming, we want to release the lock if we were holding it before. if (mIsStreaming) { mWifiLock.acquire(); } else if (mWifiLock.isHeld()) { mWifiLock.release(); } } catch (IOException ex) { Log.e("MusicService", "IOException playing next song: " + ex.getMessage()); ex.printStackTrace(); } }
From source file:de.qspool.clementineremote.backend.ClementinePlayerConnection.java
/** * Register the RemoteControlClient/*from ww w. ja va 2s .c o m*/ */ private void registerRemoteControlClient() { // Request AudioFocus, so the widget is shown on the lock-screen mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); mAudioManager.registerMediaButtonEventReceiver(mClementineMediaButtonEventReceiver); // Create the intent Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.setComponent(mClementineMediaButtonEventReceiver); PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(App.mApp.getApplicationContext(), 0, mediaButtonIntent, 0); // Create the client mRcClient = new RemoteControlClient(mediaPendingIntent); if (App.mClementine.getState() == Clementine.State.PLAY) { mRcClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING); } else { mRcClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED); } mRcClient.setTransportControlFlags( RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE); mAudioManager.registerRemoteControlClient(mRcClient); }
From source file:com.koma.music.service.MusicService.java
private void setUpMediaSession() { mSession = new MediaSession(this, "KomaMusic"); mSession.setCallback(new MediaSession.Callback() { @Override/*from w w w .j a v a2s . c o m*/ public void onPause() { pause(); mPausedByTransientLossOfFocus = false; } @Override public void onPlay() { play(); } @Override public void onSeekTo(long pos) { seek(pos); } @Override public void onSkipToNext() { gotoNext(true); } @Override public void onSkipToPrevious() { prev(false); } @Override public void onStop() { pause(); mPausedByTransientLossOfFocus = false; seek(0); releaseServiceUiAndStop(); } @Override public void onSkipToQueueItem(long id) { setQueuePosition((int) id); } @Override public boolean onMediaButtonEvent(@NonNull Intent mediaButtonIntent) { if (Intent.ACTION_MEDIA_BUTTON.equals(mediaButtonIntent.getAction())) { KeyEvent ke = mediaButtonIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); if (ke != null && ke.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK) { if (ke.getAction() == KeyEvent.ACTION_UP) { handleHeadsetHookClick(ke.getEventTime()); } return true; } } return super.onMediaButtonEvent(mediaButtonIntent); } }); PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(this, MediaButtonIntentReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT); mSession.setMediaButtonReceiver(pi); mSession.setFlags(MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSession.FLAG_HANDLES_MEDIA_BUTTONS); }
From source file:com.andrew.apolloMod.service.ApolloService.java
@SuppressLint({ "WorldWriteableFiles", "WorldReadableFiles" }) @Override// ww w . j a v a2 s. c o m public void onCreate() { super.onCreate(); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); ComponentName rec = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()); mAudioManager.registerMediaButtonEventReceiver(rec); Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.setComponent(rec); PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT); if (Constants.isApi14Supported()) { mRemoteControlClient = new RemoteControlClient(mediaPendingIntent); mAudioManager.registerRemoteControlClient(mRemoteControlClient); int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP; mRemoteControlClient.setTransportControlFlags(flags); } mPreferences = getSharedPreferences(APOLLO_PREFERENCES, MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE); mCardId = MusicUtils.getCardId(this); registerExternalStorageListener(); // Needs to be done in this thread, since otherwise // ApplicationContext.getPowerManager() crashes. mPlayer = new MultiPlayer(); mPlayer.setHandler(mMediaplayerHandler); reloadQueue(); notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); IntentFilter commandFilter = new IntentFilter(); commandFilter.addAction(SERVICECMD); commandFilter.addAction(TOGGLEPAUSE_ACTION); commandFilter.addAction(PAUSE_ACTION); commandFilter.addAction(NEXT_ACTION); commandFilter.addAction(PREVIOUS_ACTION); commandFilter.addAction(CYCLEREPEAT_ACTION); commandFilter.addAction(TOGGLESHUFFLE_ACTION); registerReceiver(mIntentReceiver, commandFilter); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName()); mWakeLock.setReferenceCounted(false); // If the service was idle, but got killed before it stopped itself, the // system will relaunch it. Make sure it gets stopped again in that // case. Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); }
From source file:co.shunya.gita.player.MusicService.java
/** * Starts playing the next song. If manualUrl is null, the next song will be randomly selected * from our Media Retriever (that is, it will be a random song in the user's device). If * manualUrl is non-null, then it specifies the URL or path to the song that will be played * next.// w w w.j av a 2s . co m */ void playNextSong(Long id) { if (id == null || id < 0) { throw new IllegalArgumentException("id must be non nul +ve"); } setState(State.Stopped); relaxResources(false); // release everything except MediaPlayer try { // set the source of the media player to a manual URL or path Track playingItem = mRetriever.getItem(id); createMediaPlayerIfNeeded(); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); if (playingItem == null) { Toast.makeText(this, "All Tracks of current category is been played", Toast.LENGTH_LONG).show(); processStopRequest(true); // stop everything! return; } // BusProvider.getInstance().post(playingItem); mCurrentID = id; mPlayer.setDataSource(playingItem.isDownloded() ? playingItem.getLocalUrl(this) : playingItem.getUrl()); mIsStreaming = playingItem.getUrl().startsWith("http:") || playingItem.getUrl().startsWith("https:"); mSongTitle = playingItem.getTitle(); setState(State.Preparing); updateUI(); setUpAsForeground(mSongTitle + " (loading)"); // Use the media button APIs (if available) to register ourselves for media button // events MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, mMediaButtonReceiverComponent); // Use the remote control APIs (if available) to set the playback state if (mRemoteControlClientCompat == null) { Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON); intent.setComponent(mMediaButtonReceiverComponent); mRemoteControlClientCompat = new RemoteControlClientCompat(PendingIntent.getBroadcast( this /*context*/, 0 /*requestCode, ignored*/, intent /*intent*/, 0 /*flags*/)); RemoteControlHelper.registerRemoteControlClient(mAudioManager, mRemoteControlClientCompat); } mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING); mRemoteControlClientCompat.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_STOP); // Update the remote controls mRemoteControlClientCompat.editMetadata(true) .putString(MediaMetadataRetriever.METADATA_KEY_ALBUM, "Gita") .putString(MediaMetadataRetriever.METADATA_KEY_TITLE, playingItem.getTitle()) .putBitmap(RemoteControlClientCompat.MetadataEditorCompat.METADATA_KEY_ARTWORK, mDummyAlbumArt) .apply(); // starts preparing the media player in the background. When it's done, it will call // our OnPreparedListener (that is, the onPrepared() method on this class, since we set // the listener to 'this'). // // Until the media player is prepared, we *cannot* call start() on it! mPlayer.prepareAsync(); // If we are streaming from the internet, we want to hold a Wifi lock, which prevents // the Wifi radio from going to sleep while the song is playing. If, on the other hand, // we are *not* streaming, we want to release the lock if we were holding it before. if (mIsStreaming) mWifiLock.acquire(); else if (mWifiLock.isHeld()) mWifiLock.release(); } catch (IOException ex) { Log.e("MusicService", "IOException playing next song: " + ex.getMessage()); ex.printStackTrace(); } }
From source file:com.nd.android.u.square.service.MusicPlaybackService.java
/** * Starts playing the next song. If manualUrl is null, the next song will be randomly selected * from our Media Retriever (that is, it will be a random song in the user's device). If * manualUrl is non-null, then it specifies the URL or path to the song that will be played * next./*from ww w . ja v a 2 s .co m*/ */ void playNextSong(Item playingItem) { mState = State.Stopped; relaxResources(false); // release everything except MediaPlayer try { if (null == playingItem) { playingItem = pollNextSong(mPlayingItem); if (null == playingItem) { if (sOnStateChangedListener != null) { sOnStateChangedListener.onPlayListIsEmpty(); } return; } mPlayingItem = playingItem; if (null != sOnStateChangedListener) sOnStateChangedListener.onCurrentPlayingItemChanged(mPlayingItem); } // set the source of the media player a a content URI createMediaPlayerIfNeeded(); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.setDataSource(playingItem.getUrl()); mIsStreaming = true; mSongTitle = playingItem.title; mState = State.Preparing; setUpAsForeground(mSongTitle + ""); // Use the media button APIs (if available) to register ourselves for media button // events MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, mMediaButtonReceiverComponent); // Use the remote control APIs (if available) to set the playback state if (mRemoteControlClientCompat == null) { Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON); intent.setComponent(mMediaButtonReceiverComponent); mRemoteControlClientCompat = new RemoteControlClientCompat(PendingIntent .getBroadcast(this /*context*/, 0 /*requestCode, ignored*/, intent /*intent*/, 0 /*flags*/ )); RemoteControlHelper.registerRemoteControlClient(mAudioManager, mRemoteControlClientCompat); } mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING); mRemoteControlClientCompat.setTransportControlFlags( RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_STOP); // Update the remote controls mRemoteControlClientCompat.editMetadata(true) .putString(MediaMetadataRetriever.METADATA_KEY_TITLE, playingItem.title) .putLong(MediaMetadataRetriever.METADATA_KEY_DURATION, playingItem.duration) // TODO: fetch real item artwork .putBitmap(RemoteControlClientCompat.MetadataEditorCompat.METADATA_KEY_ARTWORK, mDummyAlbumArt) .apply(); // starts preparing the media player in the background. When it's done, it will call // our OnPreparedListener (that is, the onPrepared() method on this class, since we set // the listener to 'this'). // // Until the media player is prepared, we *cannot* call start() on it! mPlayingItem.bufferedPercent = 0; mPlayer.prepareAsync(); if (null != sOnStateChangedListener) sOnStateChangedListener.onPlayerPreparing(mPlayingItem); // If we are streaming from the internet, we want to hold a Wifi lock, which prevents // the Wifi radio from going to sleep while the song is playing. If, on the other hand, // we are *not* streaming, we want to release the lock if we were holding it before. if (mIsStreaming) mWifiLock.acquire(); else if (mWifiLock.isHeld()) mWifiLock.release(); } catch (IOException ex) { Log.e(TAG, "IOException playing next song: " + ex.getMessage(), ex); } }
From source file:com.andrew.apollo.MusicPlaybackService.java
/** * Initializes the remote control client *//*w ww . j a v a 2 s . c o m*/ private void setUpRemoteControlClient() { final Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.setComponent(mMediaButtonReceiverComponent); mRemoteControlClient = new RemoteControlClient(PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT)); try { if (mAudioManager != null) { mAudioManager.registerRemoteControlClient(mRemoteControlClient); } } catch (Throwable t) { // seems like this doesn't work on some devices where it requires MODIFY_PHONE_STATE // which is a permission only given to system apps, not third party apps. } // Flags for the media transport control that this client supports. int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP; flags |= RemoteControlClient.FLAG_KEY_MEDIA_POSITION_UPDATE; mRemoteControlClient.setOnGetPlaybackPositionListener(this::position); mRemoteControlClient.setPlaybackPositionUpdateListener(this::seek); mRemoteControlClient.setTransportControlFlags(flags); }