PageRenderTime 32ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/samples/browseable/MediaRouter/src/com.example.android.mediarouter/player/MainActivity.java

https://gitlab.com/vicidroiddev/platform_development
Java | 724 lines | 574 code | 91 blank | 59 comment | 71 complexity | d24df23233295e8a81f8d87cea479f16 MD5 | raw file
  1. /*
  2. * Copyright (C) 2013 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.example.android.mediarouter.player;
  17. import android.app.PendingIntent;
  18. import android.content.ComponentName;
  19. import android.content.Context;
  20. import android.content.Intent;
  21. import android.media.AudioManager;
  22. import android.media.AudioManager.OnAudioFocusChangeListener;
  23. import android.media.RemoteControlClient;
  24. import android.net.Uri;
  25. import android.os.Build;
  26. import android.os.Bundle;
  27. import android.os.Environment;
  28. import android.os.Handler;
  29. import android.os.SystemClock;
  30. import android.support.v4.app.FragmentManager;
  31. import android.support.v4.view.MenuItemCompat;
  32. import android.support.v7.app.ActionBarActivity;
  33. import android.support.v7.app.MediaRouteActionProvider;
  34. import android.support.v7.app.MediaRouteDiscoveryFragment;
  35. import android.support.v7.media.MediaControlIntent;
  36. import android.support.v7.media.MediaItemStatus;
  37. import android.support.v7.media.MediaRouteSelector;
  38. import android.support.v7.media.MediaRouter;
  39. import android.support.v7.media.MediaRouter.Callback;
  40. import android.support.v7.media.MediaRouter.ProviderInfo;
  41. import android.support.v7.media.MediaRouter.RouteInfo;
  42. import android.util.Log;
  43. import android.view.KeyEvent;
  44. import android.view.Menu;
  45. import android.view.MenuItem;
  46. import android.view.View;
  47. import android.view.View.OnClickListener;
  48. import android.view.ViewGroup;
  49. import android.widget.AdapterView;
  50. import android.widget.AdapterView.OnItemClickListener;
  51. import android.widget.ArrayAdapter;
  52. import android.widget.ImageButton;
  53. import android.widget.ListView;
  54. import android.widget.SeekBar;
  55. import android.widget.SeekBar.OnSeekBarChangeListener;
  56. import android.widget.TabHost;
  57. import android.widget.TabHost.OnTabChangeListener;
  58. import android.widget.TabHost.TabSpec;
  59. import android.widget.TextView;
  60. import android.widget.Toast;
  61. import com.example.android.mediarouter.R;
  62. import com.example.android.mediarouter.provider.SampleMediaRouteProvider;
  63. import java.io.File;
  64. /**
  65. * <h3>Media Router Support Activity</h3>
  66. * <p/>
  67. * <p>
  68. * This demonstrates how to use the {@link MediaRouter} API to build an
  69. * application that allows the user to send content to various rendering
  70. * targets.
  71. * </p>
  72. */
  73. public class MainActivity extends ActionBarActivity {
  74. private static final String TAG = "MainActivity";
  75. private static final String DISCOVERY_FRAGMENT_TAG = "DiscoveryFragment";
  76. private MediaRouter mMediaRouter;
  77. private MediaRouteSelector mSelector;
  78. private LibraryAdapter mLibraryItems;
  79. private PlaylistAdapter mPlayListItems;
  80. private TextView mInfoTextView;
  81. private ListView mLibraryView;
  82. private ListView mPlayListView;
  83. private ImageButton mPauseResumeButton;
  84. private ImageButton mStopButton;
  85. private SeekBar mSeekBar;
  86. private boolean mPaused;
  87. private boolean mNeedResume;
  88. private boolean mSeeking;
  89. private RemoteControlClient mRemoteControlClient;
  90. private ComponentName mEventReceiver;
  91. private AudioManager mAudioManager;
  92. private PendingIntent mMediaPendingIntent;
  93. private final Handler mHandler = new Handler();
  94. private final Runnable mUpdateSeekRunnable = new Runnable() {
  95. @Override
  96. public void run() {
  97. updateProgress();
  98. // update UI every 1 second
  99. mHandler.postDelayed(this, 1000);
  100. }
  101. };
  102. private final SessionManager mSessionManager = new SessionManager("app");
  103. private Player mPlayer;
  104. private final MediaRouter.Callback mMediaRouterCB = new MediaRouter.Callback() {
  105. // Return a custom callback that will simply log all of the route events
  106. // for demonstration purposes.
  107. @Override
  108. public void onRouteAdded(MediaRouter router, RouteInfo route) {
  109. Log.d(TAG, "onRouteAdded: route=" + route);
  110. }
  111. @Override
  112. public void onRouteChanged(MediaRouter router, RouteInfo route) {
  113. Log.d(TAG, "onRouteChanged: route=" + route);
  114. }
  115. @Override
  116. public void onRouteRemoved(MediaRouter router, RouteInfo route) {
  117. Log.d(TAG, "onRouteRemoved: route=" + route);
  118. }
  119. @Override
  120. public void onRouteSelected(MediaRouter router, RouteInfo route) {
  121. Log.d(TAG, "onRouteSelected: route=" + route);
  122. mPlayer = Player.create(MainActivity.this, route);
  123. mPlayer.updatePresentation();
  124. mSessionManager.setPlayer(mPlayer);
  125. mSessionManager.unsuspend();
  126. registerRemoteControlClient();
  127. updateUi();
  128. }
  129. @Override
  130. public void onRouteUnselected(MediaRouter router, RouteInfo route) {
  131. Log.d(TAG, "onRouteUnselected: route=" + route);
  132. unregisterRemoteControlClient();
  133. PlaylistItem item = getCheckedPlaylistItem();
  134. if (item != null) {
  135. long pos = item.getPosition() +
  136. (mPaused ? 0 : (SystemClock.elapsedRealtime() - item.getTimestamp()));
  137. mSessionManager.suspend(pos);
  138. }
  139. mPlayer.updatePresentation();
  140. mPlayer.release();
  141. }
  142. @Override
  143. public void onRouteVolumeChanged(MediaRouter router, RouteInfo route) {
  144. Log.d(TAG, "onRouteVolumeChanged: route=" + route);
  145. }
  146. @Override
  147. public void onRoutePresentationDisplayChanged(MediaRouter router, RouteInfo route) {
  148. Log.d(TAG, "onRoutePresentationDisplayChanged: route=" + route);
  149. mPlayer.updatePresentation();
  150. }
  151. @Override
  152. public void onProviderAdded(MediaRouter router, ProviderInfo provider) {
  153. Log.d(TAG, "onRouteProviderAdded: provider=" + provider);
  154. }
  155. @Override
  156. public void onProviderRemoved(MediaRouter router, ProviderInfo provider) {
  157. Log.d(TAG, "onRouteProviderRemoved: provider=" + provider);
  158. }
  159. @Override
  160. public void onProviderChanged(MediaRouter router, ProviderInfo provider) {
  161. Log.d(TAG, "onRouteProviderChanged: provider=" + provider);
  162. }
  163. };
  164. private final OnAudioFocusChangeListener mAfChangeListener = new OnAudioFocusChangeListener() {
  165. @Override
  166. public void onAudioFocusChange(int focusChange) {
  167. if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
  168. Log.d(TAG, "onAudioFocusChange: LOSS_TRANSIENT");
  169. } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
  170. Log.d(TAG, "onAudioFocusChange: AUDIOFOCUS_GAIN");
  171. } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
  172. Log.d(TAG, "onAudioFocusChange: AUDIOFOCUS_LOSS");
  173. }
  174. }
  175. };
  176. @Override
  177. protected void onCreate(Bundle savedInstanceState) {
  178. // Be sure to call the super class.
  179. super.onCreate(savedInstanceState);
  180. if (savedInstanceState != null) {
  181. mPlayer = (Player) savedInstanceState.getSerializable("mPlayer");
  182. }
  183. // Get the media router service.
  184. mMediaRouter = MediaRouter.getInstance(this);
  185. // Create a route selector for the type of routes that we care about.
  186. mSelector =
  187. new MediaRouteSelector.Builder().addControlCategory(MediaControlIntent
  188. .CATEGORY_LIVE_AUDIO).addControlCategory(MediaControlIntent
  189. .CATEGORY_LIVE_VIDEO).addControlCategory(MediaControlIntent
  190. .CATEGORY_REMOTE_PLAYBACK).addControlCategory(SampleMediaRouteProvider
  191. .CATEGORY_SAMPLE_ROUTE).build();
  192. // Add a fragment to take care of media route discovery.
  193. // This fragment automatically adds or removes a callback whenever the activity
  194. // is started or stopped.
  195. FragmentManager fm = getSupportFragmentManager();
  196. DiscoveryFragment fragment =
  197. (DiscoveryFragment) fm.findFragmentByTag(DISCOVERY_FRAGMENT_TAG);
  198. if (fragment == null) {
  199. fragment = new DiscoveryFragment(mMediaRouterCB);
  200. fragment.setRouteSelector(mSelector);
  201. fm.beginTransaction().add(fragment, DISCOVERY_FRAGMENT_TAG).commit();
  202. } else {
  203. fragment.setCallback(mMediaRouterCB);
  204. fragment.setRouteSelector(mSelector);
  205. }
  206. // Populate an array adapter with streaming media items.
  207. String[] mediaNames = getResources().getStringArray(R.array.media_names);
  208. String[] mediaUris = getResources().getStringArray(R.array.media_uris);
  209. mLibraryItems = new LibraryAdapter();
  210. for (int i = 0; i < mediaNames.length; i++) {
  211. mLibraryItems.add(new MediaItem(
  212. "[streaming] " + mediaNames[i], Uri.parse(mediaUris[i]), "video/mp4"));
  213. }
  214. // Scan local external storage directory for media files.
  215. File externalDir = Environment.getExternalStorageDirectory();
  216. if (externalDir != null) {
  217. File list[] = externalDir.listFiles();
  218. if (list != null) {
  219. for (int i = 0; i < list.length; i++) {
  220. String filename = list[i].getName();
  221. if (filename.matches(".*\\.(m4v|mp4)")) {
  222. mLibraryItems.add(new MediaItem(
  223. "[local] " + filename, Uri.fromFile(list[i]), "video/mp4"));
  224. }
  225. }
  226. }
  227. }
  228. mPlayListItems = new PlaylistAdapter();
  229. // Initialize the layout.
  230. setContentView(R.layout.sample_media_router);
  231. TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
  232. tabHost.setup();
  233. String tabName = getResources().getString(R.string.library_tab_text);
  234. TabSpec spec1 = tabHost.newTabSpec(tabName);
  235. spec1.setContent(R.id.tab1);
  236. spec1.setIndicator(tabName);
  237. tabName = getResources().getString(R.string.playlist_tab_text);
  238. TabSpec spec2 = tabHost.newTabSpec(tabName);
  239. spec2.setIndicator(tabName);
  240. spec2.setContent(R.id.tab2);
  241. tabName = getResources().getString(R.string.statistics_tab_text);
  242. TabSpec spec3 = tabHost.newTabSpec(tabName);
  243. spec3.setIndicator(tabName);
  244. spec3.setContent(R.id.tab3);
  245. tabHost.addTab(spec1);
  246. tabHost.addTab(spec2);
  247. tabHost.addTab(spec3);
  248. tabHost.setOnTabChangedListener(new OnTabChangeListener() {
  249. @Override
  250. public void onTabChanged(String arg0) {
  251. updateUi();
  252. }
  253. });
  254. mLibraryView = (ListView) findViewById(R.id.media);
  255. mLibraryView.setAdapter(mLibraryItems);
  256. mLibraryView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
  257. mLibraryView.setOnItemClickListener(new OnItemClickListener() {
  258. @Override
  259. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  260. updateButtons();
  261. }
  262. });
  263. mPlayListView = (ListView) findViewById(R.id.playlist);
  264. mPlayListView.setAdapter(mPlayListItems);
  265. mPlayListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
  266. mPlayListView.setOnItemClickListener(new OnItemClickListener() {
  267. @Override
  268. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  269. updateButtons();
  270. }
  271. });
  272. mInfoTextView = (TextView) findViewById(R.id.info);
  273. mPauseResumeButton = (ImageButton) findViewById(R.id.pause_resume_button);
  274. mPauseResumeButton.setOnClickListener(new OnClickListener() {
  275. @Override
  276. public void onClick(View v) {
  277. mPaused = !mPaused;
  278. if (mPaused) {
  279. mSessionManager.pause();
  280. } else {
  281. mSessionManager.resume();
  282. }
  283. }
  284. });
  285. mStopButton = (ImageButton) findViewById(R.id.stop_button);
  286. mStopButton.setOnClickListener(new OnClickListener() {
  287. @Override
  288. public void onClick(View v) {
  289. mPaused = false;
  290. mSessionManager.stop();
  291. }
  292. });
  293. mSeekBar = (SeekBar) findViewById(R.id.seekbar);
  294. mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
  295. @Override
  296. public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
  297. PlaylistItem item = getCheckedPlaylistItem();
  298. if (fromUser && item != null && item.getDuration() > 0) {
  299. long pos = progress * item.getDuration() / 100;
  300. mSessionManager.seek(item.getItemId(), pos);
  301. item.setPosition(pos);
  302. item.setTimestamp(SystemClock.elapsedRealtime());
  303. }
  304. }
  305. @Override
  306. public void onStartTrackingTouch(SeekBar seekBar) {
  307. mSeeking = true;
  308. }
  309. @Override
  310. public void onStopTrackingTouch(SeekBar seekBar) {
  311. mSeeking = false;
  312. updateUi();
  313. }
  314. });
  315. // Schedule Ui update
  316. mHandler.postDelayed(mUpdateSeekRunnable, 1000);
  317. // Build the PendingIntent for the remote control client
  318. mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  319. mEventReceiver =
  320. new ComponentName(getPackageName(), SampleMediaButtonReceiver.class.getName());
  321. Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
  322. mediaButtonIntent.setComponent(mEventReceiver);
  323. mMediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);
  324. // Create and register the remote control client
  325. registerRemoteControlClient();
  326. // Set up playback manager and player
  327. mPlayer = Player.create(MainActivity.this, mMediaRouter.getSelectedRoute());
  328. mSessionManager.setPlayer(mPlayer);
  329. mSessionManager.setCallback(new SessionManager.Callback() {
  330. @Override
  331. public void onStatusChanged() {
  332. updateUi();
  333. }
  334. @Override
  335. public void onItemChanged(PlaylistItem item) {
  336. }
  337. });
  338. updateUi();
  339. }
  340. private void registerRemoteControlClient() {
  341. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
  342. // Create the RCC and register with AudioManager and MediaRouter
  343. mAudioManager.requestAudioFocus(mAfChangeListener, AudioManager.STREAM_MUSIC,
  344. AudioManager.AUDIOFOCUS_GAIN);
  345. mAudioManager.registerMediaButtonEventReceiver(mEventReceiver);
  346. mRemoteControlClient = new RemoteControlClient(mMediaPendingIntent);
  347. mAudioManager.registerRemoteControlClient(mRemoteControlClient);
  348. mMediaRouter.addRemoteControlClient(mRemoteControlClient);
  349. SampleMediaButtonReceiver.setActivity(MainActivity.this);
  350. mRemoteControlClient.setTransportControlFlags(RemoteControlClient
  351. .FLAG_KEY_MEDIA_PLAY_PAUSE);
  352. mRemoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
  353. }
  354. }
  355. private void unregisterRemoteControlClient() {
  356. // Unregister the RCC with AudioManager and MediaRouter
  357. if (mRemoteControlClient != null) {
  358. mRemoteControlClient.setTransportControlFlags(0);
  359. mAudioManager.abandonAudioFocus(mAfChangeListener);
  360. mAudioManager.unregisterMediaButtonEventReceiver(mEventReceiver);
  361. mAudioManager.unregisterRemoteControlClient(mRemoteControlClient);
  362. mMediaRouter.removeRemoteControlClient(mRemoteControlClient);
  363. SampleMediaButtonReceiver.setActivity(null);
  364. mRemoteControlClient = null;
  365. }
  366. }
  367. public boolean handleMediaKey(KeyEvent event) {
  368. if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
  369. switch (event.getKeyCode()) {
  370. case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: {
  371. Log.d(TAG, "Received Play/Pause event from RemoteControlClient");
  372. mPaused = !mPaused;
  373. if (mPaused) {
  374. mSessionManager.pause();
  375. } else {
  376. mSessionManager.resume();
  377. }
  378. return true;
  379. }
  380. case KeyEvent.KEYCODE_MEDIA_PLAY: {
  381. Log.d(TAG, "Received Play event from RemoteControlClient");
  382. if (mPaused) {
  383. mPaused = false;
  384. mSessionManager.resume();
  385. }
  386. return true;
  387. }
  388. case KeyEvent.KEYCODE_MEDIA_PAUSE: {
  389. Log.d(TAG, "Received Pause event from RemoteControlClient");
  390. if (!mPaused) {
  391. mPaused = true;
  392. mSessionManager.pause();
  393. }
  394. return true;
  395. }
  396. case KeyEvent.KEYCODE_MEDIA_STOP: {
  397. Log.d(TAG, "Received Stop event from RemoteControlClient");
  398. mPaused = false;
  399. mSessionManager.stop();
  400. return true;
  401. }
  402. default:
  403. break;
  404. }
  405. }
  406. return false;
  407. }
  408. @Override
  409. public boolean onKeyDown(int keyCode, KeyEvent event) {
  410. return handleMediaKey(event) || super.onKeyDown(keyCode, event);
  411. }
  412. @Override
  413. public boolean onKeyUp(int keyCode, KeyEvent event) {
  414. return handleMediaKey(event) || super.onKeyUp(keyCode, event);
  415. }
  416. @Override
  417. public void onStart() {
  418. // Be sure to call the super class.
  419. super.onStart();
  420. }
  421. @Override
  422. public void onPause() {
  423. // pause media player for local playback case only
  424. if (!mPlayer.isRemotePlayback() && !mPaused) {
  425. mNeedResume = true;
  426. mSessionManager.pause();
  427. }
  428. super.onPause();
  429. }
  430. @Override
  431. public void onResume() {
  432. // resume media player for local playback case only
  433. if (!mPlayer.isRemotePlayback() && mNeedResume) {
  434. mSessionManager.resume();
  435. mNeedResume = false;
  436. }
  437. super.onResume();
  438. }
  439. @Override
  440. public void onDestroy() {
  441. // Unregister the remote control client
  442. unregisterRemoteControlClient();
  443. mPaused = false;
  444. mSessionManager.stop();
  445. mPlayer.release();
  446. super.onDestroy();
  447. }
  448. @Override
  449. public boolean onCreateOptionsMenu(Menu menu) {
  450. // Be sure to call the super class.
  451. super.onCreateOptionsMenu(menu);
  452. // Inflate the menu and configure the media router action provider.
  453. getMenuInflater().inflate(R.menu.sample_media_router_menu, menu);
  454. MenuItem mediaRouteMenuItem = menu.findItem(R.id.media_route_menu_item);
  455. MediaRouteActionProvider mediaRouteActionProvider =
  456. (MediaRouteActionProvider) MenuItemCompat.getActionProvider(mediaRouteMenuItem);
  457. mediaRouteActionProvider.setRouteSelector(mSelector);
  458. // Return true to show the menu.
  459. return true;
  460. }
  461. private void updateProgress() {
  462. // Estimate content position from last status time and elapsed time.
  463. // (Note this might be slightly out of sync with remote side, however
  464. // it avoids frequent polling the MRP.)
  465. int progress = 0;
  466. PlaylistItem item = getCheckedPlaylistItem();
  467. if (item != null) {
  468. int state = item.getState();
  469. long duration = item.getDuration();
  470. if (duration <= 0) {
  471. if (state == MediaItemStatus.PLAYBACK_STATE_PLAYING ||
  472. state == MediaItemStatus.PLAYBACK_STATE_PAUSED) {
  473. mSessionManager.updateStatus();
  474. }
  475. } else {
  476. long position = item.getPosition();
  477. long timeDelta =
  478. mPaused ? 0 : (SystemClock.elapsedRealtime() - item.getTimestamp());
  479. progress = (int) (100.0 * (position + timeDelta) / duration);
  480. }
  481. }
  482. mSeekBar.setProgress(progress);
  483. }
  484. private void updateUi() {
  485. updatePlaylist();
  486. updateRouteDescription();
  487. updateButtons();
  488. }
  489. private void updatePlaylist() {
  490. mPlayListItems.clear();
  491. for (PlaylistItem item : mSessionManager.getPlaylist()) {
  492. mPlayListItems.add(item);
  493. }
  494. mPlayListView.invalidate();
  495. }
  496. private void updateRouteDescription() {
  497. RouteInfo route = mMediaRouter.getSelectedRoute();
  498. mInfoTextView.setText(
  499. "Currently selected route:" + "\nName: " + route.getName() + "\nProvider: " +
  500. route.getProvider().getPackageName() + "\nDescription: " +
  501. route.getDescription() + "\nStatistics: " +
  502. mSessionManager.getStatistics());
  503. }
  504. private void updateButtons() {
  505. MediaRouter.RouteInfo route = mMediaRouter.getSelectedRoute();
  506. // show pause or resume icon depending on current state
  507. mPauseResumeButton.setImageResource(
  508. mPaused ? R.drawable.ic_action_play : R.drawable.ic_action_pause);
  509. // disable pause/resume/stop if no session
  510. mPauseResumeButton.setEnabled(mSessionManager.hasSession());
  511. mStopButton.setEnabled(mSessionManager.hasSession());
  512. // only enable seek bar when duration is known
  513. PlaylistItem item = getCheckedPlaylistItem();
  514. mSeekBar.setEnabled(item != null && item.getDuration() > 0);
  515. if (mRemoteControlClient != null) {
  516. mRemoteControlClient.setPlaybackState(mPaused ? RemoteControlClient.PLAYSTATE_PAUSED :
  517. RemoteControlClient.PLAYSTATE_PLAYING);
  518. }
  519. }
  520. private PlaylistItem getCheckedPlaylistItem() {
  521. int count = mPlayListView.getCount();
  522. int index = mPlayListView.getCheckedItemPosition();
  523. if (count > 0) {
  524. if (index < 0 || index >= count) {
  525. index = 0;
  526. mPlayListView.setItemChecked(0, true);
  527. }
  528. return mPlayListItems.getItem(index);
  529. }
  530. return null;
  531. }
  532. public static final class DiscoveryFragment extends MediaRouteDiscoveryFragment {
  533. private static final String TAG = "DiscoveryFragment";
  534. private Callback mCallback;
  535. public DiscoveryFragment() {
  536. mCallback = null;
  537. }
  538. public DiscoveryFragment(Callback cb) {
  539. mCallback = cb;
  540. }
  541. public void setCallback(Callback cb) {
  542. mCallback = cb;
  543. }
  544. @Override
  545. public Callback onCreateCallback() {
  546. return mCallback;
  547. }
  548. @Override
  549. public int onPrepareCallbackFlags() {
  550. // Add the CALLBACK_FLAG_UNFILTERED_EVENTS flag to ensure that we will
  551. // observe and log all route events including those that are for routes
  552. // that do not match our selector. This is only for demonstration purposes
  553. // and should not be needed by most applications.
  554. return super.onPrepareCallbackFlags() | MediaRouter.CALLBACK_FLAG_UNFILTERED_EVENTS;
  555. }
  556. }
  557. private static final class MediaItem {
  558. public final String mName;
  559. public final Uri mUri;
  560. public final String mMime;
  561. public MediaItem(String name, Uri uri, String mime) {
  562. mName = name;
  563. mUri = uri;
  564. mMime = mime;
  565. }
  566. @Override
  567. public String toString() {
  568. return mName;
  569. }
  570. }
  571. private final class LibraryAdapter extends ArrayAdapter<MediaItem> {
  572. public LibraryAdapter() {
  573. super(MainActivity.this, R.layout.media_item);
  574. }
  575. @Override
  576. public View getView(int position, View convertView, ViewGroup parent) {
  577. final View v;
  578. if (convertView == null) {
  579. v = getLayoutInflater().inflate(R.layout.media_item, null);
  580. } else {
  581. v = convertView;
  582. }
  583. final MediaItem item = getItem(position);
  584. TextView tv = (TextView) v.findViewById(R.id.item_text);
  585. tv.setText(item.mName);
  586. ImageButton b = (ImageButton) v.findViewById(R.id.item_action);
  587. b.setImageResource(R.drawable.ic_suggestions_add);
  588. b.setTag(item);
  589. b.setOnClickListener(new OnClickListener() {
  590. @Override
  591. public void onClick(View v) {
  592. if (item != null) {
  593. mSessionManager.add(item.mUri, item.mMime);
  594. Toast.makeText(MainActivity.this, R.string.playlist_item_added_text,
  595. Toast.LENGTH_SHORT).show();
  596. }
  597. }
  598. });
  599. return v;
  600. }
  601. }
  602. private final class PlaylistAdapter extends ArrayAdapter<PlaylistItem> {
  603. public PlaylistAdapter() {
  604. super(MainActivity.this, R.layout.media_item);
  605. }
  606. @Override
  607. public View getView(int position, View convertView, ViewGroup parent) {
  608. final View v;
  609. if (convertView == null) {
  610. v = getLayoutInflater().inflate(R.layout.media_item, null);
  611. } else {
  612. v = convertView;
  613. }
  614. final PlaylistItem item = getItem(position);
  615. TextView tv = (TextView) v.findViewById(R.id.item_text);
  616. tv.setText(item.toString());
  617. ImageButton b = (ImageButton) v.findViewById(R.id.item_action);
  618. b.setImageResource(R.drawable.ic_suggestions_delete);
  619. b.setTag(item);
  620. b.setOnClickListener(new OnClickListener() {
  621. @Override
  622. public void onClick(View v) {
  623. if (item != null) {
  624. mSessionManager.remove(item.getItemId());
  625. Toast.makeText(MainActivity.this, R.string.playlist_item_removed_text,
  626. Toast.LENGTH_SHORT).show();
  627. }
  628. }
  629. });
  630. return v;
  631. }
  632. }
  633. }